[英]How to deep populate with self-referential model Mongoose
我正在嘗試首先使用文章 model 中的以下字段填充多個級別:
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment"
}
]
然后從評論 model 中:
replies : [ {
type: Schema.Types.ObjectId,
ref: "Comment"
}]
我已經參考了 ZCCADCDEDB567ABAE643E15DCF0974E503Z 文檔關於跨多個級別和許多其他資源填充以創建我的查詢:
const getArticle = async (req, res) => {
const slug = { slug: req.params.slug};
const page = "Article";
let article = await Article.findOne(slug)
.populate({
path: "comments",
model: "Comment",
options: {
sort: { date: -1}
},
populate:{
path: "replies",
model: "Comment",
options: {
sort: { date: -1}
}
}
})
console.log("articlePop:", article);
res.render("show", { page, article });
};
當我在 Mongosh 中檢查文檔時,所有內容都會顯示為正確的 ref _id,但是查詢不會填充回復字段:
{
_id: new ObjectId("630f83777b023e0af292dd4a"),
username: 'noffler',
date: '31/08/2022, 16:51:19',
title: 'the napoleonic wars',
article: 'the return of Napoleon',
likes: 0,
dislikes: 0,
comments: [
{
_id: new ObjectId("630f83917b023e0af292dd50"),
username: 'noffler',
date: '31/08/2022, 16:51:45',
comment: 'some say money is bad for the soul',
likes: 0,
dislikes: 0,
replies: [Array],
__v: 0
}
],
slug: 'the-napoleonic-wars',
__v: 0
}
如果有人能指出我正確的方向,我將不勝感激。 親切的問候。
也許1 - 你在最后錯過了 add exec
function
let article = await Article.findOne(slug)
.populate({
path: "comments",
model: "Comment",
options: {
sort: { date: -1}
},
populate:{
path: "replies",
model: "Comment",
options: {
sort: { date: -1}
}
}
}).exec(function(err, docs) {});
或 2 - 您應該在回復 object 周圍添加 []
let article = await Article.findOne(slug)
.populate({
path: "comments",
model: "Comment",
options: {
sort: { date: -1}
},
populate:[{
path: "replies",
model: "Comment",
options: {
sort: { date: -1}
}
}]
})
我希望它會幫助你
為什么不考慮使用 MongoDB 的聚合?
我會極力推薦它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.