我正在模拟我的微博应用程序用户之间的“朋友”关系。它看起来像这样:
在 user.js 文件中
var db = require('mongoose')
, Schema = db.Schema
, ObjectId=Schema.ObjectId;
var userSchema = new Schema({
name:{firstname:String,surname:String},
birthdate:String,
email:String,
posts: [new Schema({
timestamp:Date,
post:{type: ObjectId, ref: 'Post'}
})],
friends: [new Schema({
friend: {type:ObjectId, ref:'User'}
})]
});
module.exports = db.model('User', userSchema);
在 post.js 文件中
var db = require('mongoose')
, Schema = db.Schema,
ObjectId=Schema.ObjectId;
var postSchema = new Schema({
title:String,
content:String,
});
module.exports = db.model('Post', eventSchema);
我想要实现的是获取所有当前用户的朋友,他们的帖子数组的嵌入式文档已经填充。我笨拙地尝试了这个功能:
function getUserFriendsPost(req, res) {
var count = 0;
var output = new Array();
User.findOne({
_id: req.params.id
}, function(err, user) {
for (var i = 0; i < user.friends.length; i++) {
User.findOne({
_id: user.friends[i].friend
}).populate('posts.post').exec(function(err, post) {
output.push(post);
count++;
if (count==user.friends.length) {
res.send(output);
}
});
}
});
}
相反,我得到的是正确返回的朋友数组,但帖子的元素具有 null 值,如下所示:
[
{
"_id": "4fd5e5f3e45fd10100000004",
"birthdate": "11/11/1911",
"email": "blablabla@gmail.com",
"friends": [],
"posts": [
{
"timestamp": "2012-04-12T16:47:14.576Z",
"post": null,
"_id": "4f870712c488cf0100000081"
},
{
"timestamp": "2012-04-12T16:48:42.282Z",
"post": null,
"_id": "4f87076ac488cf01000000a3"
},
{
"timestamp": "2012-04-12T16:56:26.062Z",
"post": null,
"_id": "4f87093ac488cf0100000117"
}
"name": {
"firstname": "John",
"surname": "Doe"
}
}
]
有什么我忽略了填充机制还是应该采用不同的方法?谢谢