Search code examples
node.jsmongodbmongoosepopulatemongoose-populate

Match specific value in mongoose populate


Following is the schema of a user collection:

const Mongoose = require('mongoose')

const Schema = Mongoose.Schema

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String
    },
    supporterOf: [{
        type: Schema.Types.ObjectId,
        ref: 'individual',
        required: false
    }],
})

module.exports = Mongoose.model('user', userSchema);

I want to populate 'supporterOf' which is a collection of individual (ref: individual). The 'supporterOf' contains an array of ObjectId. I am having the problem of matching the specific objectId with that ObjectId array. Can anyone suggest me how I can match specific ObjectId with an array of ObjectIds in populate function?


Solution

  • You have a reference of 'individual' in supporterOf and you want to populate only relevant object from the array of individuals? If this is right case then do the following:

    YourUserModel.findById(userId, function (err, user) {
            console.log(user)
         }).populate({
            path: 'supporterOf',
            match: {
               yourObjectOfIndividualDocument: yourMatchingIdOfIndividual
            }
         })
         .exec()
    

    Replace yourObjectOfIndividualDocument: yourMatchingIdOfIndividual by name: 'abcd'. Here name is the field of Individual document not of User document.