如何以mongooserecursion的方式获取模型中的所有对象

想象这两个嵌套的mongoose模型,一个包含候选人列表的投票

var candidateSchema = new Schema({ name: String }); var voteSchema = new Schema({ candidates: [{ type: Schema.Types.ObjectId, ref: 'Candidate' }] }); voteSchema.methods.addCandidate = function addCandidate(newCandidate, callback) { this.candidates.addToSet(newCandidate); this.save(callback); }; var Vote = mongoose.model('Vote', voteSchema); var vote = new Vote(); var Candidate = mongoose.model('Candidate', candidateSchema); var candidate = new Candidate({ name: 'Guillaume Vincent' }); vote.addCandidate(candidate); console.log(vote); // { _id: 53d613fdadfd08d9ebea6f88, candidates: [ 53d68476fc78cb55f5d91c17] } console.log(vote.toJSON()); // { _id: 53d613fdadfd08d9ebea6f88, candidates: [ 53d68476fc78cb55f5d91c17] } 

如果我使用candidates: [candidateSchema]而不是candidates: [{ type: Schema.Types.ObjectId, ref: 'Candidate' }]然后console.log(vote); 显示:

 { _id: 53d613fdadfd08d9ebea6f88, candidates: [ { _id: 53d613fdadfd08d9ebea6f86, name: 'Guillaume Vincent' } ] } 

我的问题是:

candidates: [{ type: Schema.Types.ObjectId, ref: 'Candidate' }]我怎么能recursion地附加到模型的所有对象? 与candidates: [candidateSchema]同样的行为candidates: [candidateSchema]

我没有使用embedded式模式,因为我希望在更新我的候选人时更新我的​​投票(请参阅https://stackoverflow.com/a/14418739/866886 )

你看过mongoose对人口的支持吗?

例如:

 Vote.find().populate('candidates').exec(callback); 

将为每个id填充具有完整Candidate对象的candidates数组。