这是关于Mongoose嵌套的populate方法。我曾尝试使用populate方法来填充文档,但仍有问题。
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);
我希望最终得到用户的结果,会议的嵌套参与者已解决
{
"_id": "53e87d7bc4088daefc3d5adc",
"email": "david@email.com",
"fullName": "david",
"lastModifiedDate": "2014-08-11T08:23:23.359Z",
"meetings": [{
"_id": "53e8abf8dd1662000041af5d",
"topic": "Linkedin",
"_creator": "53e89187cbed0f0000c534b1",
"meetingdate": "12/12/2014",
"attendees": [{
"email": "david@email.com",
"fullName": "david",
"_id": "53e87d7bc4088daefc3d5adc",
}, {
"email": "john@email.com",
"fullName": "john",
"_id": "53e87d7bc4088daefc3dbaua",
}]
}],
}
我知道填充查询在哪里出错。
我甚至试过这个,但现在最终的回复本身并没有起作用。
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);
}
);
})
答案 0 :(得分:1)
这是嵌套人口的正确方法
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);
}
);
})
您可以咨询mongoose docs mongoose population