franksprings
franksprings

Reputation: 55

Mongoose population returns empty document

I'm trying to utilize the Mongoose population feature. Writing data is not the issue; all object ids are stored in the parent (Account) document. I verified this with a simple Account.find() query. However, when I'm trying to query 'accounts' and to populate it with related video objects, the 'videos' object in the account document is empty. I read all the possible resources and documentation on this subject and I'm kind of stuck on this topic. Can anybody help me out? Thanks!

Schema's

var videoSchema = new Schema({
   url: String,
   status: String,
});

mongoose.model('Video', videoSchema );

var accountSchema = new Schema({
    name: { type: String, required: true },
    videos: [{ type: Schema.Types.ObjectId, ref: 'Video' }]
});

mongoose.model('Account', accountSchema ); 

Write data

new Video({ userAgent: referrer: req.headers.['url'], status: "created" }).save(function(err, video){
  Account.update({ _id: req.headers['appid'] }, {$push: { videos: [ video._id ] } },    function (err, account){
     if(err) console.log(JSON.stringify(err));
  });
}); 

Retrieve data using populate

Account.findById(req.params.id).populate('videos').exec(function(err, account){
   console.log(JSON.stringify(account));
   res.render('./account/show', account);
}); 

Upvotes: 0

Views: 175

Answers (1)

robertklep
robertklep

Reputation: 203286

Your $push statement is pushing an array onto an array, which makes the population fail.

Use this instead:

{ $push: { videos: video._id } }

If you eventually have an array of videos that you want to merge with an existing videos property of an account, you can use $each:

{ $push: { videos : { $each : [ video1._id, video2._id, ... ] } } }

Upvotes: 3

Related Questions