1
1
1972912017-12-09 14:55:01
MongoDB
197291, 2017-12-09 14:55:01

How to replace/update an object in an array?

Hello. Tell me, there is a MongoDB collection, documents with the following structure:

{
name:'Bob',
items:[{
    id:12
    name:'...',
    lastName:'..'
  },
  {
    id:13
    name:'...',
    lastName:'..'
  }]
}

It is necessary in all documents in which there is an object with id = 12, to replace it with another one, or to update certain fields. I'm using moongoose, but it's possible with native nodejs driver. Tried it this way:
Model.update({ 'items.id': id }, {$set:{
    'items.$[element]':obj,
  }}, {multi:true}, function(err, doc){
     console.log('doc', doc);
  });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uncle Fedor, 2017-12-09
@didiaFiodor

On vanilla js, but the logic should somehow be the same

(currdat = "plus",
data = {name:"major",items:[{id:12,name:'extra'},
{id:13,name:'basic'}]},
function(param=12)
{return data.items[0].id==12?data.items[0].name=currdat:"not found"}()
)
//вернет "plus"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question