When i populate a reference in a collection, the embedded documents in the referenced collection show up as [Object] instead of the actual document.
More details
I have a Song Schema
var songSchema=new Schema({
songName:String
});
An Album Schema
var albumSchema=new Schema({
title:String,
favs:Number,
songs:[songSchema]
})
and a Playlist Schema which references the albums.
var playlistSchema=new Schema({
title:String,
items: { type: Schema.ObjectId, ref: 'Album' }
})
Now when i run the following query
Playlist
.find()
.populate('items')
.exec(function (err, playlists) {
if (err) return handleError(err);
console.log("Result:"+playlists);
})
i get the following result
Result:{ _id: 53d6b605842416b83b5fe472,
title: 'Sad',
items:
{ _id: 53d6b605842416b83b5fe471,
title: 'Awaz',
favs: 500,
__v: 0,
songs: [ [Object], [Object] ] },
__v: 0 }
Notice how the songs array has an array of [Object] instead of the actual embedded objects. How do i get actual documents to show up ?
The "songs" are nested more than 2 levels, so by default the output is represented by "[Object"]. Try doing this:
playlists[0].songs.forEach(function (song) {
console.log(song);
});
IF you are using express.
app.get('/playlists', function (req, res, next) {
mongoose.model('Playlist').find().populate('items').exec(function (err, docs) {
if (err) return next(err);
res.json(docs);
})
});