imagine these two nested mongoose models, a Vote containing a list of Candidates
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] }
If I use candidates: [candidateSchema] instead of candidates: [{ type: Schema.Types.ObjectId, ref: 'Candidate' }] then console.log(vote); display :
{
_id: 53d613fdadfd08d9ebea6f88,
candidates: [ { _id: 53d613fdadfd08d9ebea6f86, name: 'Guillaume Vincent' } ]
}
My question is :
With candidates: [{ type: Schema.Types.ObjectId, ref: 'Candidate' }] how can I get recursively all objects attached to a model ? same behavior with candidates: [candidateSchema]
I'm not using embedded schema because I want my Vote to be updated when I update my Candidate (see http://stackoverflow.com/a/14418739/866886)
Have you looked at Mongoose's support for population?
For example:
Vote.find().populate('candidates').exec(callback);
will populate the candidates array with the full Candidate object for each id.