how to populate nested schema in Mongodb correctly

13 Views Asked by At

here was what i tried. for me it seems correct but the problem is it comes with the _ids only and not including the other fields that makes up the schema Class, Department and Level.

Here is my schema the specific part of my schema.

 Department: {
    type: Object,
    require: true,
    Name: { type: Schema.Types.ObjectId, ref: "Department", require:true },
    Level: { type: Schema.Types.ObjectId, ref: "Level" , require:true},
    Class: { type: Schema.Types.ObjectId, ref: "Class" , require:true},
  },

Here is my controller:

 (
  const find_id = await Student.findById({ _id: id })
    .select(["Name", "Surname", "Gender", "Email", "Address", "Department","Level", "Class"])
    .populate("Department", "Name")
    .populate("Department.Level" )
    .populate("Department.Class");

Here is my result:

"student": {
    "_id": "64e32afc1c22ff84509bb386",
    "Name": "Mrs Lucrese",
    "Surname": "chayie",
    "Gender": "female",
    "Email": "[email protected]",
    "Address": {
        "city": "yaounde",
        "country": "cameroon"
    },
    "Department": {
        "Name": "64df588a5325cc02fc18204d",
        "Level": "64b9d1cb7d3529d9d9011c75",
        "Class": "64df594d5325cc02fc18205f"
    }
},
"message": "success"
0

There are 0 best solutions below