我正在尝试返回文档和子文档的完整数据对象。它返回的是文档和子文档的ObjectID。我尝试了多个填充语句,它也无法正常工作。我错过了什么?
用户架构
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');
}
});
示例答案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
注意:正在填充user_id,但不包括commentor_id。
答案 0 :(得分:1)
只是一个解释
如上所述here:
在mongoose> = 3.6中,我们可以传递一个以空格分隔的路径名字符串 填充。在3.6之前,您必须执行populate()方法 多次。
所以如果你这样说就可以了:
.populate('user_id' 'comment.commentor_id')
而不是逗号所用的
答案 1 :(得分:0)
我找到了解决问题的方法。我填充的方式是错误的。我所做的是将两个填充数据放在1个填充语句
中.populate('user_id','comment.commentor_id')
应该以这种方式编写。
.populate('user_id').populate('comment.commentor_id')
答案 2 :(得分:0)
这有效:填充(' user_id comment.commentor_id')