I am starting out with mongodb and 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'). What I am trying to do is query a single post and also a single group using there unique ids. findById()
returns null. Is there a way that I can query this objects using just there respective id's.
Try this, it should solve your issue.
(send a single-post _id
to get your expected data)
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.