0

I have a Schema like this:

const NoteClusterSchema = new Schema({
   noteInfo: [{
        title: String,
        Description: String,
        authors:[{
          name: String, Id: String
        }]
   }],
   idGroup: String //this is the group of the people that are working on the proyect
}, {timestamps:true});

An example of noteInfo would be

noteInfo: [{
  title: "Hello",
  Description: "Hello World",
  authors:[
     {name: "Marcelo", id: "1234123123"},
     {name: "Pancho", id: "12341345344"}
  ]
}]

How can I update, for example, in the authors array specifically the name of "Marcelo"? (suppose that it is if the user changes it's name. I know that in this specific case I could put just the _id, but in my real Schema it isn't a user the thing I want to update)

I thought of something like this:

await NoteClusterSchema.updateMany({idGroup: req.body.idGroup}, 
                {
                    noteInfo: {$push: {authors: {name: 
                    req.body.name}}}
             })

But in this way, it won't know which of all the noteInfo arrays update or it would create a new authors array, and changing noteInfo: {$push: $push: {noteInfo: will only create a new noteInfo array.

So, how could I update this specific object in an array inside another array with the UpdateMany method?

1

1 Answer 1

1

findOneAndUpdate with the $set option should solve your problem:

NoteClusterSchema.findOneAndUpdate(
    {idGroup: req.body.idGroup},
    {$set: {"noteInfo.$[element].value": "YOUR_NEW_NAME" } },
    {
        arrayFilters: [{ "element.name": "Marcelo" }],
        new: true
    }
)

Note: You have to add the arrayFilters option in order to target the specific element in the array.

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

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

Comments

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.