1

In a mongoose document I have a array of objects, something like this :

{
    name : 'helloWorld',
    arr : [
        { a : 'id1', b : 'sampleValue1', c: 'sampleValue2'},
        { a : 'id2', b: 'tempValue1', c:'tempValue2'}
    ]
}

In the array of objects 'arr' I want to update all the values of field 'b' and 'c' with specific values, how can I do that elegantly?
I know for a single element of the array I can do (it works) :

Model.updateOne(
{
  name : 'helloWorld;,
 'arr.a' : 'id1',
},
{
  'arr.$.b' : 'newB',
  'arr.$.c' : 'newC',
}
);

But how to do it elegantly for the entire array ?
I know I can do it using multiple queries via forEach looping for each of the 'arr.a' field, but I want an elegant preferable single query method for this.

  • https://stackoverflow.com/questions/15691224/mongoose-update-values-in-array-of-objects Does this answer your question? – Joel Hager Jul 21 '21 at 05:29

0 Answers0