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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Marcelo Potty
  • 315
  • 1
  • 5
  • 10
  • 1
    Does this answer your question? [Update nested array element in mongodb](https://stackoverflow.com/questions/58953960/update-nested-array-element-in-mongodb) – Joe Apr 29 '20 at 05:10

1 Answers1

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/

Luis Orbaiceta
  • 443
  • 4
  • 15