Boom
Boom

Reputation: 21

How to update a object inside array which is present in a object which is present in an array in mongoose?

I've got a document like this,

[
    {
        "id": 1,
        "comments": [
            {
                "mail": "[email protected]",
                "Comment": "This product well worth the money"
            }
            {
                "mail": "[email protected]",
                "Comment": "Excellent Product"
            }
        ]
    },

    {
        "id": 2,
        "comments": [
            {
                "mail": "[email protected]",
                "Comment": "This product well worth the money"
            }
            {
                "mail": "[email protected]",
                "Comment": "Excellent Product"
            }
        ]
    }
]

Now I need to change only the Comment with mail "[email protected]" which is inside the comments array of the object having the id "1".

So the hierarchy looks like,

  1. Find Object with id:1
  2. Find an object with mail:[email protected] inside comments array,
  3. Update the Comment of the particular Object

This is the query I tried to update but doesn't work

  modal.findOneAndUpdate(
      { id: 1, comments: { mail: "[email protected]"} },
      {
        $set: {
          "comments.$.Comment": "New Comment",
        },
      }
    );

Upvotes: 0

Views: 125

Answers (2)

Yong Shun
Yong Shun

Reputation: 51485

You can use arrayFilters to update the nested document in the array as well.

db.collection.update({
  id: 1
},
{
  $set: {
    "comments.$[comment].Comment": "New Comment",
    
  }
},
{
  arrayFilters: [
    {
      "comment.mail": "[email protected]"
    }
  ]
})

Sample Mongo Playground

Upvotes: 1

1sina1
1sina1

Reputation: 1086

change comments: { mail: "[email protected]"} to 'comments.mail': "[email protected]"

Upvotes: 2

Related Questions