Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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": "raj@gmail.com",
                "Comment": "This product well worth the money"
            }
            {
                "mail": "janu@gmail.com",
                "Comment": "Excellent Product"
            }
        ]
    },

    {
        "id": 2,
        "comments": [
            {
                "mail": "raj@gmail.com",
                "Comment": "This product well worth the money"
            }
            {
                "mail": "janu@gmail.com",
                "Comment": "Excellent Product"
            }
        ]
    }
]

Now I need to change only the Comment with mail "raj@gmail.com" which is inside the comments array of the object having the id "1".

So the hierarchy looks like,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Find Object with id:1
  2. Find an object with mail:raj@gmail.com 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: "raj@gmail.com"} },
      {
        $set: {
          "comments.$.Comment": "New Comment",
        },
      }
    );

>Solution :

change comments: { mail: "raj@gmail.com"} to 'comments.mail': "raj@gmail.com"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading