Mongoose以级联方式填充嵌入式文档

时间:2012-07-05 09:32:16

标签: javascript nosql mongoose

我正在为我的微博应用用户之间的“朋友”关系建模。它看起来像这样:

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);
                }
            });
        }

    });

}

我得到的是expert数组正确返回但是帖子的元素值为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"
        }
    }
]

有什么东西让我忽略了填充机制或者我应该采用不同的方法吗? 谢谢

1 个答案:

答案 0 :(得分:2)

运气好的话,我们会在Mongoose 3.0中进行递归填充。在此之前,请考虑从帖子中复制您想要的数据(可能只是标题)并将其存储如下:

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,
        title: String,
        post: {type: ObjectId, ref: 'Post'}
    })],
    friends: [new Schema({
        friend: {type: ObjectId, ref: 'User'}
    })]
});

module.exports = db.model('User', userSchema);

然后你可以做一个常规的:

User.findOne({_id: req.params.id}).populate('friends').exec(function(err, user) { ... })