1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, if it solves your issue, please mark the answer as a solution ( with the tick mark from where the answer starts)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.