[英]Mongoose query populate match id of find elements
我正在嘗試用另一個模型的數據填充模型。 這兩個模型看起來像這樣:
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
,並使用來自已創建的帖子的id_post
== _id
comments
填充它們。 像這樣的東西:
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()
我放棄匹配的原因是當你想根據特定字段進行過濾時應該使用匹配,在你的情況下,你可以使用匹配來獲得只有type ='something'的注釋。
populate應該有效,因為當您插入注釋時,您將其綁定到其帖子。
有關正確使用populate的方法的更多信息可以在這里找到 - Mongoose Query Population
發布數據應按以下方式保留:
{
body: "some body",
type: "some type",
_comments: [12346789, 234567890, ...]
}
有關ref將如何保留的方式的更多信息 - 與文檔參考的一對多關系
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.