Search code examples
mongodbmongoosepostmanmongoose-populate

How to populate array of objects in mongoose


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?


Solution

  • I just solved it by chaining the populate method directly after the Course.find({}).

    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 });
        }
    };
    

    From the docs for Populate:

    We may populate a single document, multiple documents, a plain object, multiple plain objects, or all objects returned from a query.