Search code examples
mongodbmongoosemongoose-populate

Populating only specific fields in mongoose


I have a document like this:

Info collection:

{
  infoType: "Appointment",
  contact: ObjectId("5baa28a3f1268917e9220138"),
}

Contact collection:

{
  name: "ABC",
  email: "abc@def.com"
}

And I want to populate only contact name in query by using populate method in mongoose.


Solution

  • Try this it will might help you to get exactly what you want.

    infoModel.find({contactId: ObjectId("5baa28a3f1268917e9220138")})
    .populate('contact', "name email")
    .then(infoDetails => {
        console.log("Info Details -> ", infoDetails)
    }).catch(err => {
        console.log("Error Occured -> ", err)
    })
    

    Refer document for further knowledge.