First post here, so hello to everyone!
I’m having trouble with mongoose populate because it’s apparently doing nothing. I’m going straight to the code.
Here are my models:
Space
const spaceSchema = Schema(
{
user: {
type: Schema.Types.ObjectId,
required: true,
ref: "User",
},
name: {
type: String,
required: true,
},
days: [{ type: Schema.Types.ObjectId, refPath: "Day" }],
},
{
versionKey: false,
timestamps: true
},
);
const Space = mongoose.model("Space", spaceSchema);
module.exports = Space;
Day
const daySchema = Schema(
{
space: { type: Schema.Types.ObjectId, refPath: "Space" },
date: {
type: String,
required: true,
},
water: {
type: Boolean,
},
fertilizer: {
type: Boolean,
},
transplant: {
type: Boolean,
},
comment: {
type: String,
},
},
{
versionKey: false,
timestamps: true
},
);
const Day = mongoose.model("Day", daySchema);
module.exports = Day;
And the part of the controller where I have the getSpace route (/api/spaces/:id):
const getSpace = asyncHandler(async (req, res) => {
const space = await Space.findById(req.params.id).populate("days");
res.status(200).json(space);
});
And this is the result I get:
{
"_id": "63580115978dbf8f2f5a7a50",
"user": "63501ab84613855834daa4ef",
"name": "spaceName",
"days": []
}
I tried many things, but all the results were the same.
Let me know if you need any other part of the code.
Thank you all
I expect the result to look something like this
"space": {
"_id": "63580115978dbf8f2f5a7a50",
"user": "63501ab84613855834daa4ef",
"name": "spaceName",
"days": [
{
"_id": "63581af565aed8cad3210046",
"space": "63580115978dbf8f2f5a7a50",
"date": "29/10/2022",
"water": true,
"fertilizer": true,
"transplant": false,
"comment": "This is a comment.",
"createdAt": ...,
"updatedAt": ...
},
{
"_id": "63581af565aed8cad3210046",
"space": "63580115978dbf8f2f5a7a50",
"date": "29/10/2022",
"water": false,
"fertilizer": false,
"transplant": true,
"comment": "This is a comment.",
"createdAt": ...,
"updatedAt": ...
}
]
}