[英]How to query embedded documents in an embedded array mongodb
I am starting out with mongodb and mongoose.我从 mongodb 和 mongoose 开始。 This is what my db looks like这就是我的数据库的样子
[
{
_id: "5fd0f98751e33831d8ef4899"
date: "01/01/2020, 11:47:00 AM"
groups: [
{
_id: "5fd0f98751e33831d8ef489a"
name: "Eyob"
profession: "doctor"
posts: [
{
_id: "5fd0f98751e33831d8ef489b"
numberOfLikes: 16
numberOfShares: "2 Shares"
},
{
_id: "5fd0f98751e33831d8ef489c"
numberOfLikes: 26
numberOfShares: "7 Shares"
}
]
},
{
_id: "5fd0f98751e33831d8ef489d"
name: "Abel"
profession: "teacher"
posts: [
{
_id: "5fd0f98751e33831d8ef489e"
numberOfLikes: 16
numberOfShares: "2 Shares"
},
{
_id: "5fd0f98751e33831d8ef489f"
numberOfLikes: 26
numberOfShares: "7 Shares"
}
]
}
]
},
{
_id: "5fd0f98751e33831d8ef489d"
date: "01/02/2020, 11:47:00 AM"
groups: [// an array of groups as the above one //]
}
]
so for every groups array there is a group object that contains a posts array that contains a post object.('This might be confusing').因此,对于每个组数组,都有一个组 object 包含一个包含帖子 object 的帖子数组。(“这可能会令人困惑”)。 What I am trying to do is query a single post and also a single group using there unique ids.我想要做的是使用唯一的 id 查询单个帖子和单个组。 findById()
returns null. findById()
返回 null。 Is there a way that I can query this objects using just there respective id's.有没有一种方法可以让我只使用相应的 id 来查询这些对象。
Try this, it should solve your issue.试试这个,它应该可以解决你的问题。
(send a single-post _id
to get your expected data) (发送单个帖子_id
以获取您的预期数据)
const {id}=req.params;
YourDataModel.findOne({"groups.posts._id":id}, {"groups.posts._id.$":true})
.then(data=>data?res.send({
groupId:data.groups[0]._id,
groupName:data.groups[0].name,
post:data.groups[0].posts.filter(e=>e._id===id)[0]
}): res.send("Not found!"))
.catch(err=>res.send(err))
You also can get all the posts of the group (relevant to that post) with the same code, just do res.send(data)
or make necessary modification where necessary.您还可以使用相同的代码获取该组的所有帖子(与该帖子相关),只需执行res.send(data)
或在必要时进行必要的修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.