Home > Enterprise >  Node.js- Add new field in array of Mongodb object
Node.js- Add new field in array of Mongodb object

Time:01-10

I have a collection of users that has an array of multiple plates :

users : [
{
_id: '61234XXX'
plates: [
 {
   _id: '123'
   'color': 'orange'
 },
 {
   _id: '124'
   'color': 'blue'
 }
]
},
{
_id: '63456XXX'
plates: [
 {
   _id: '321'
   'color': 'orange'
 },
 {
   _id: '432'
   'color': 'green'
 }
]
}
]

I'm trying to figure out a way to add a new field to the all current plate objects for every user:

I've got to this:

  await User.findOneAndUpdate(
      { _id: '63456XXX' },
      {
        $set : {
          [`plates.0.plateStyle`]: "testValue"
        }
      }
  )

Tho this works it's not fit for purpose. Is there a better way I can iterate over this?

CodePudding user response:

You can try this query:

Here you are using array filters to tell mongo: "Where you find an object with _id: "61234XXX" and exists the plates then, there, get the document (elem) which match that plates is not empty (to get all) and add plateStyle".

await User.updateMany({
  _id: "61234XXX",
  plates: {
    $exists: true
  }
},
{
  $set: {
    "plates.$[elem].plateStyle": "testValue"
  }
},
{
  arrayFilters: [
    {
      elem: { $ne: [ "$plates", [] ] }
    }
  ]
})

Example here

Also if you are finding by _id you won't need updateMany since _id is unique and only will be 1 or 0 results.

  • Related