Gene Lim Gene Lim - 3 months ago 13
Node.js Question

MongoDB: Multiple populate subdocuments not being returned

I am trying to return a full data object of the documents and subdocuments. What it is returning is the documents and the ObjectID of the subdocuments. I have tried multiple populate statement, it is also not working. What am I missing?

User Schema

module.exports = function (connection) {
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var user_fb = new mongoose.Schema({
name: String,
location: String,
fb_id: Number,
fb_image: String
});

return connection.model('User_Fb', user_fb);;
}


Feed Schema

module.exports = function (connection) {
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var locationSchema = new Schema({
fb_location: String,
coordinates:[]
});

var commentSchema = new Schema({
data: String,
image: [{ type : String }],
commentor_id: { type: Schema.Types.ObjectId, ref: 'User_Fb' },
created_at:{ type : Date, default: Date.now }
});

var feed_postSchema = new Schema({
user_id: { type: Schema.Types.ObjectId, ref: 'User_Fb' },
content: String,
location: [locationSchema],
comment: [commentSchema],
image: [{ type : String }],
created_at: { type : Date, default: Date.now }
});

feed_postSchema.index({'location.coordinates':'2dsphere'});
return connection.model('Feed_Post', feed_postSchema);
}


Server.js

app.get('/get_feed', function(req,res){
if(req.param('distance') !== 'undefined'){
Feed_Post.find(
{
'location.coordinates':
{
$nearSphere:
{
$geometry:
{
type:'Point',
coordinates:[req.param('lng'),req.param('lat')]
}
,$maxDistance:req.param('distance')
}
}
}).populate('user_id','comment.commentor_id').sort({created_at:1}).exec(function(err, result) {
if (err) { return console.log(err); }
res.json(result);
});
}else{
res.json('error');
}
});


Sample Answer Json:

"_id" : ObjectId("562856e23ffdbb5f41510bee"),
"user_id" : {
ObjectId("5625d5d200ef06265deabfbe"),
'fb_id': 123456
'fb_image': "image_url"
'location': ""
'name': "Name Hello"
}
"content" : "Testing another post with comment",
"created_at" : ISODate("2015-10-22T03:24:18.697Z"),
"image" : [ ],
"comment" : [
{
"commentor_id" : ObjectId("5625d5d200ef06265deabfbe"),
"data" : "CraY comment",
"_id" : ObjectId("562856f23ffdbb5f41510bf0"),
"created_at" : ISODate("2015-10-22T03:24:34.546Z"),
"image" : [
"testimg_URL"
]
},
],
"location" : [
{
"fb_location" : "Earth",
"_id" : ObjectId("562856e23ffdbb5f41510bef"),
"coordinates" : [
100.2803235,
5.3314547
]
}
],
"__v" : 0


Note: user_id is being populated but commentor_id is not.

Answer

I have found a solution to my problem. The way I populate was wrong. What I did was by putting two populate data in 1 populate statement

.populate('user_id','comment.commentor_id')

It should have been written this way instead.

.populate('user_id').populate('comment.commentor_id')
Comments