Search code examples
node.jsarraysexpressmongoosesubdocument

update a field in a array inside another array in mongoose document


process = {
  num: 1,
  notes: [ 
    { sequence: 1,
      user: 199283,
      votes: [
         {_id: 113222, user: 122334, text: 'something' },
         {_id: 441122, user: 123321, text: 'other something' },
      ]}, 
    { sequence: 2,
      user: 199213,
      votes: [
         {_id: 111122, user: 121564, text: 'something2' },
         {_id: 222221, user: 126621, text: 'other something2' },
         {_id: 333333, user: 123321, text: 'other something2' }
      ]}
  ]
}

A need to update the field text with _id = 333333 in the sub-array votes.

I tried to use Model.findAndUpdate(). But, I found in the internet examples for update with 1 levels of arrays.

How could I use mongoose to update a field in a array inside another array in a document?


Solution

  • After finding the document you can make any changes to the object and then call .save() on the document to make the same changes in the database. I used forEach callbacks but you can also use a library like lodash to change the text.

    let document = await Model.find({_id:2134315})
    
    document.notes.forEach((note)=>{
      note.votes.forEach((vote)=>{
        if(vote._id==333333) vote.text="YOUR NEW TEXT HERE"
      })
    })
    
    document.save()
    

    This may not work if you are using populated references but from what you described it did not seem like it.