我正在尝试用另一个模型的数据填充一个模型。这两个模型看起来像这样:
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,
});
我想找到所有 posts
并用 comments
填充它们,这些 id_post
== _id
来自 founded帖子。像这样:
Post.find({}).populate({
path: '_comments',
select: 'body',
match: { post_id: Post._id }
options: { limit: 5 }
})
.exec(function (err, posts){...});
最佳答案
首先,您编写的代码几乎没有问题。 如果每个帖子可能有很多评论,你应该在你的模式之间实现一对多关系,你可以通过用 [] 包围评论 ref 来做到这一点
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()
我放弃匹配的原因是当你想根据特定字段进行过滤时应该使用匹配,在你的情况下你可以使用匹配来只获得类型='something'的评论。
populate 应该可以工作,因为当您插入评论时,您已将其绑定(bind)到它的帖子。
可以在此处找到有关正确使用 populate 方法的更多信息 - Mongoose Query Population
发布数据应按以下方式持久化:
{
body: "some body",
type: "some type",
_comments: [12346789, 234567890, ...]
}
有关 ref 的持久化方式的更多信息 - One-to-Many Relationships with Document References
关于node.js - Mongoose 查询填充查找元素的匹配 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438134/