need help resolving this issue,I am trying to use the populate method to replace Id's with a reerenced document, but when I output the returned result, the documents are not returned, instead the Id values still remain. here is my schema and detail code to clearify, thanks
var CommentSchema=new mongoose.Schema({
comment:{type:String},
accountId:{type:mongoose.Schema.ObjectId, ref:'Account'}
});
var StatusSchema=new mongoose.Schema({
comments:[CommentSchema],
accountId:{type:mongoose.Schema.ObjectId, ref:'Account'},//should be replaced with docement
status:{type:String}
});
ACCOUNT SCHEMA
var AccountSchema=new mongoose.Schema({
email:{type:String,unique:true},
password:{type:String},
name:{
first:{type:String},
last:{type:String},
full:{type:String}
},
contacts:[Contact],
status:[Status]
});
var Account=mongoose.model('Account',AccountSchema);
var Comment=mongoose.model('Comment',CommentSchema);
var Status=mongoose.model('Status', StatusSchema);
//This is how I save new Comments
app.post('/accounts/:id/status', function(req, res) {
var accountId = req.params.id;
models.Account.findById(accountId, function(account) {
account.save(function(err){
if (err) throw err;
var status=new models.Account.Status();
status.accountId=accountId;
status.status=req.param('status', '');
status.save(function(err){
account.status.push(status);
account.save(function(err){
if(err)console.log(err)
else
console.log('successful! status save...')
});
});
});
});
res.send(200);
});
//QUERY -I expect this query to replace the accountId with the referenced document, but when the query runs, accountId still holds the id rather than the referenced document
var getActivity= function(accountId,callback){
Account.findOne({_id:accountId}).populate('Status.accountId').exec(function(err, items) {
console.log('result is:'+items);
});
}
You're using Status in AccountSchema before it's defined. However, you should actually be using StatusSchema (the schema) instead of Status (the model) in the definition of AccountSchema anyway.
Try this instead:
var AccountSchema=new mongoose.Schema({
email:{type:String,unique:true},
password:{type:String},
name:{
first:{type:String},
last:{type:String},
full:{type:String}
},
contacts:[Contact],
status:[StatusSchema]
});