Home > Software design >  Mongoose .populate() is not working with node.js app
Mongoose .populate() is not working with node.js app

Time:10-26

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 :D

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": ...
            }
        ]
    }

CodePudding user response:

use ref instead of refPath
like this

const storySchema = Schema({
  days: { type: Schema.Types.ObjectId, ref: 'Day' },
  space: { type: Schema.Types.ObjectId, ref: "Space" },
});

CodePudding user response:

const mongoose = require('mongoose');

const { Schema } = mongoose;

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);

Story.
  findOne({ title: 'Casino Royale' }).
  populate('author').
  exec(function (err, story) {
    if (err) return handleError(err);
    console.log('The author is %s', story.author.name);
    // prints "The author is Ian Fleming"
  });

Reference : https://mongoosejs.com/docs/populate.html

  • Related