Home > Net >  How to populate array of objects in mongoose
How to populate array of objects in mongoose

Time:01-11

I have this code -

const getAllCourses = async (req, res) => {
    const courses = await Course.find({});

    try {
        await courses.populate('professor')
        
        res.send({ status: 200, data: { courses } });
    } catch (err) {
        res.status(500).send({ status: 500, message: "Internal server error." });
    }

};

Also, this is the response I'm getting from postman -

{
    "status": 200,
    "data": {
        "courses": [
            {
                "_id": "61dc47f58f88c1a7e9bd36b6",
                "name": "Course1",
                "professor": "61dc1299431cd669faad7d0f",
                "students": [
                    {
                        "student": "61dc0b7f103b531f105e8e4c",
                        "_id": "61dc47f58f88c1a7e9bd36b7"
                    },
                    {
                        "student": "61dc220885886a9f1d8e94d0",
                        "_id": "61dc47f58f88c1a7e9bd36b8"
                    }
                ],
                "createdAt": "2022-01-10T14:51:33.313Z",
                "updatedAt": "2022-01-10T14:51:33.313Z",
                "__v": 0
            },
            {
                "_id": "61dc47fb8f88c1a7e9bd36bf",
                "name": "Course2",
                "professor": "61dc1299431cd669faad7d0f",
                "students": [
                    {
                        "student": "61dc0b7f103b531f105e8e4c",
                        "_id": "61dc47fb8f88c1a7e9bd36c0"
                    },
                    {
                        "student": "61dc220885886a9f1d8e94d0",
                        "_id": "61dc47fb8f88c1a7e9bd36c1"
                    }
                ],
                "createdAt": "2022-01-10T14:51:39.704Z",
                "updatedAt": "2022-01-10T14:51:39.704Z",
                "__v": 0
            }
        ]
    }
}

Now what I'm trying to do is to populate the professor and the students but it doesn't seem to work.

I tried populating "courses.professor", "course.professor", "professor" but nothing worked for me.

What am I missing?

CodePudding user response:

Here is an example of how this can be done for a document with an array friends on it:

User.
  findOne({ name: 'Val' }).
  populate({
    path: 'friends',
    // Get friends of friends - populate the 'friends' array for every friend
    populate: { path: 'friends' }
  });

CodePudding user response:

I just solved it by chaining the populate method directly after the Course.find({}) and it just worked, I'm not sure why though.

Solution:

const getAllCourses = async (req, res) => {
    const courses = await Course.find({}).populate('professor').populate('students.student');

    try {
        res.send({ status: 200, data: { courses } });        
    } catch (err) {
        res.status(500).send({ status: 500, message: err.message });
    }
};
  •  Tags:  
  • Related