CoolestAth
CoolestAth

Reputation: 31

Mongoose : Populate nested schemas

This is regarding the Mongoose nested populate method. I have tried to use populate method to get the document populated, but still having an issue.

var userSchema = Schema({    
email: {type: String,required: true,unique: true}, 
fullName: String,   
meetings: [{
    type: Schema.Types.ObjectId,
    ref: 'Meeting'
    }]
});

userSchema.statics.findById = function (id, callback) {
this.findOne({
    _id: id
}).populate({
    path: 'meetings',
    select: '_creator topic attendees'
}).populate({
    path: 'meetings.attendees',
    model: Attendee
})
    .exec(callback);
};

var meetingSchema = Schema({
_creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
},
topic: String,    
attendees: [attendeeSchema]
});


var attendeeSchema = Schema({
_id: false,
attendee: {type: String,required: true,ref: 'User'}
})

var Meeting = mongoose.model('Meeting', meetingSchema);
var User = mongoose.model('User', userSchema);
var Attendee = mongoose.model('Attendee', attendeeSchema);

I would like to get a user's result in the end with meeting's nested attendees resolved

{
"_id": "53e87d7bc4088daefc3d5adc",
"email": "[email protected]",
"fullName": "david",
"lastModifiedDate": "2014-08-11T08:23:23.359Z",
"meetings": [{
    "_id": "53e8abf8dd1662000041af5d",
    "topic": "Linkedin",
    "_creator": "53e89187cbed0f0000c534b1",
    "meetingdate": "12/12/2014",
    "attendees": [{
        "email": "[email protected]",
        "fullName": "david",
         "_id": "53e87d7bc4088daefc3d5adc",
    }, {
        "email": "[email protected]",
        "fullName": "john",
         "_id": "53e87d7bc4088daefc3dbaua",
    }]
}],

}

Any idea where am i going wrong with the populate query.

I tried even this, but now the final response itself is not working.

User.findById(userid, function (err, doc) {
                if (err) {return res.send(err);}
        Meeting.populate(doc.meetings, {
                path: 'attendees'
            },
            function (err, response) {
                if (err) {return res.send(err);}
                res.send(response);
            }
        );
    })

Upvotes: 2

Views: 1302

Answers (1)

Asad Fida
Asad Fida

Reputation: 216

This is the correct way for the nested population

User.findById(userid, function (err, doc) {
                if (err) {return res.send(err);}
        User.populate(doc, {
                path: 'Meeting'
            },
            function (err, response) {
                if (err) {return res.send(err);}
                res.send(response);
            }
        );
    })

you can consult with the mongoose docs mongoose population

Upvotes: 1

Related Questions