[英]how to populate a mongoDb documents from another collections with unique Ids
I am trying to populate documents from another collection into the documents that is meant to be returned.我正在尝试将另一个集合中的文档填充到要返回的文档中。 Eg例如
{
msg:"success",
data:[
{
_id: "61d97498dc11d6d80db7212e",
feedbackTitle: "Testing",
comment:[
{
_id: "61d974e0dc11d6d80db7213b",
sender: "61d87a94b43d99126841187d",
subcomment:[
{
content: "This is my first subcomment",
sender: {
_id: "61d713dd0e5ff818f6701345",
name: "bamigboye",
email: "bamigboye@gmail.com",
pic: "/uploads/Battery.PNG"
},
owner: {
_id: "61d87a94b43d99126841187d",
name: "titi",
email: "titi@gmail.com",
pic: "/uploads/Battery.PNG"
},
_id: "61d97c96af284a97b3bb557a",
}
]
}
],
}
]
}
am able to join and populate the above objects with this code here我能够在此处使用此代码加入并填充上述对象
const feedbacks = await Feedback.find({})
.populate("user", "_id name pic email")
.populate({
path: "comment",
populate: {
path: "sender",
model: "User",
select: "_id name pic email",
},
populate: [
{
path: "subcomment",
populate: {
path: "sender owner",
model: "User",
select: "_id name pic email",
},
},
],
});
res.status(StatusCodes.OK).json({ msg: "success", data: feedbacks });
now the problem I have right now is that, inside the comment array above, the sender property value is not being populated and whereas I did populate it according to the code above, I read in mongoose docs about a scenario like this, that it only the second query that will be effected but am totally new to the backend world coming from the frontend world and I have no idea how to structure my code in a scenario like these for the comment.sender to be populated.现在我现在遇到的问题是,在上面的注释数组中,发送者属性值没有被填充,虽然我确实根据上面的代码填充了它,但我在 mongoose 文档中读到了这样一个场景,它只是第二个查询将受到影响,但对于来自前端世界的后端世界来说是全新的,我不知道如何在这样的场景中构造我的代码以填充 comment.sender。
After so many debugging and reading on how to join same path with different properties, I read the mongoose docs populating multiple paths
and received an insight of how to go about it.在对如何加入具有不同属性的相同路径进行了大量调试和阅读之后,我阅读了mongoose 文档populating multiple paths
,并获得了有关如何使用 go 的见解。 so I interchanged the way have chained the populate path placing the user populate between two same path and it worked.所以我交换了链接填充路径的方式,将用户填充在两个相同的路径之间并且它起作用了。
const feedbacks = await Feedback.find({})
.populate({
path: "comment",
populate: {
path: "sender",
model: "User",
select: "_id name pic email",
},
})
.populate({ path: "user", select: "_id name email pic" })
.populate({
path: "comment",
populate: [
{
path: "subcomment",
populate: {
path: "sender owner",
model: "User",
select: "_id name pic email",
},
},
],
});res.status(StatusCodes.OK).json({ msg: "success", data: feedbacks });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.