Home > Software engineering >  Edit multiple objects in array using mongoose (MongoDB)
Edit multiple objects in array using mongoose (MongoDB)

Time:03-15

So I tried several ways, but I can't, I can modify several objects with the same key but I can't modify any with different keys, if anyone can help me is quite a complex problem

{ 
  id: 123, 
  "infos": [ 
    { name: 'Joe', value: 'Disabled', id: 0 }, 
    { name: 'Adam', value: 'Enabled', id: 0 }
  ]
};

In my database I have a collection with an array and several objects inside which gives this.

I want to modify these objects, filter by their name and modify the value.

To give you a better example, my site returns me an object with the new data, and I want to modify the database object with the new object, without clearing the array, the name key never changes.

const object = [
  { name: 'Joe', value: 'Hey', id: 1 }, 
  { name: 'Adam', value: 'None', id: 1 }
];

for(const obj in object) {
  Schema.findOneAndUpdate({ id: 123 }, {
    $set: {
      [`infos.${obj}.value`]: "Test"
    }
  })
}

This code works but it is not optimized, it makes several requests, I would like to do everything in one request, and also it doesn't update the id, only the value.

If anyone can help me that would be great, I've looked everywhere and can't find anything

My schema structure

new Schema({
  id: { "type": String, "required": true, "unique": true }, 
  infos: []
})

I use the $addToSet method to insert objects into the infos array

CodePudding user response:

Maybe you look for something like this:

db.collection.update({},
{
  $set: {
   "infos.$[x].value": "test1",
   "infos.$[x].id": 10,
   "infos.$[y].value": "test2",
   "infos.$[y].id": 20
   }
 },
{
 arrayFilters: [
{
  "x.name": "Adam"
},
{
  "y.name": "Joe"
}
],
  multi: true
})

Explained:

You define arrayFilters for all names in objects you have and update the values & id in all documents ...

playground

CodePudding user response:

Try This :

   db.collection.update({
  id: 123
},
{
  $set: {
    "infos.$[].value": "Value"
  }
})
  1. The all positional $[] operator acts as a placeholder for all elements in the array field.

MongoPlayGround Link : https://mongoplayground.net/p/GFbqCbADxZ4

  • Related