2015-02-10 80 views
3

我试图用另一个模型的数据填充模型。这两个模型是这样的:猫鼬查询填充查找元素的匹配id

var postSchema = mongoose.Schema({ 
    _comments: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }, 
    type: String, 
    body: String, 
}); 

var commentSchema = mongoose.Schema({ 
    id_post: mongoose.Schema.Types.ObjectId, 
    body: String, 
}); 

我想找到所有postscommentsid_post == _id从创立帖子进行填充。这样的事情:

Post.find({}).populate({ 
    path: '_comments', 
    select: 'body', 
    match: { post_id: Post._id } 
    options: { limit: 5 } 
}) 
.exec(function (err, posts){...}); 

回答

3

首先,你写的代码有几个问题。 如果每一个帖子可以有很多意见,你应该实现你的架构之间的一个一对多的关系,你可以做到这一点通过周围用[]

var postSchema = mongoose.Schema({ 
    _comments: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Comment'} ] , 
    type: String, 
    body: String, 
}); 

id_post不仅仅是一个类型的ObjectId现场评论裁判,应该这样写:

var commentSchema = mongoose.Schema({ 
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }, 
body: String, 
}); 

当保存一个新评论确保将其连接到其职位:

var comment = new Comment({ 
    body: "Hello", 
    post: post._id // assign the _id from the post 
    }); 

comment.save(function (err) { 
    if (err) return handleError(err); 
    // thats it! 
    }); 

现在,当你想找到一个后,填充它的意见,你应该写这样的事情:

Post 
.find(...) 
.populate({ 
    path: '_comments', 
    select: 'body', 
    options: { limit: 5 } 
}) 
.exec() 

我放弃比赛的原因是当您需要根据特定的字段来筛选匹配,应使用,你的情况,你可以用匹配只能获得type ='something'的评论。

填充应该工作,因为当你插入评论时,你使债券到其帖子。

使用填入的正确方法的更多信息可以在这里找到 - Mongoose Query Population

后的数据应坚持以下方式:

{ 
    body: "some body", 
    type: "some type", 
    _comments: [12346789, 234567890, ...] 
} 

关于裁判会在这里坚持的方式的更多信息 - One-to-Many Relationships with Document References

+0

'postSchema'中的'_comments'应该包含类似'[{_id:Comment.id}]''的东西。或'[{id_post:Post._id}]' – TGeorge 2015-02-10 20:14:47

+0

您可以在我的回答中找到修改后的postSchema,我刚刚以正确的方式添加了commentSchema以将其与Post相关联。 – 2015-02-10 20:25:21

+0

在我的DATABASE里,一个'post'文件是什么样的? '_comments'应该包含什么? – TGeorge 2015-02-10 20:38:11