简体   繁体   中英

Edit multiple objects in array using mongoose (MongoDB)

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

Try This:

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

  2. In $in you can use dynamic array of id. Ex:

    const ids = [1,2,..n]

    db.collection.update( //Same code as it is... { arrayFilters: [ { "x.id": { $in: ids } }, ], multi: true })

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM