1

I need to perform a $addToSet on an nested array, here an example:

{
   _id: 123,
   posts:[
      {
         _id: 234,
         userid: 123 //its same id like the documents id,
         likesUser: []
      }
   ]
}

My API requires 2 parameters:

  1. The ID of the document, and the Post ID in witch post i want to add.

  2. The ID of the user that liked that post.

If a user likes an Post his User ID should be stored in likesUser.

Lets say a user likes a post. The document have the id 123, first i want to search the document with that ID. After that i want to search the post with the id 234. Now i want to store the ID of the users that liked the post in likesUser, in this case the user have the ID 5d345

{
   _id: 123,
   posts:[
      {
         _id: 234,
         userid: 123 //its same id like the documents id,
         likesUser: ["5d345"]
      }
   ]
}

How do i archieve it? I have tried it with $elemMatch but it doesnt work it throws me error over error.

bill.gates
  • 14,145
  • 3
  • 19
  • 47

1 Answers1

2

I have found out the result:

 let result = await Post.findOneAndUpdate(
    {
      _id: mongoose.Types.ObjectId(userId),
      "posts._id": mongoose.Types.ObjectId(postId)
    },
    {
      $addToSet: {
        "posts.$.likesUser": USER
      }
    }
  );
bill.gates
  • 14,145
  • 3
  • 19
  • 47