Home > Enterprise >  Mongoose findOneAndUpdate keep throwing an error when trying to update a nested object
Mongoose findOneAndUpdate keep throwing an error when trying to update a nested object

Time:10-26

This may well be me doing something wrong. I'm trying to update a nested object, but I'm failing..... well sort of.

My Mongoose model looks a bit like this:

{
root_level_stuff: 
{
......
},
Vehicles: [
{
   other_fields: {
   ..........
   },
   Id: {
     type: Number
   },
   Recycle: {
     type: Boolean
   }]
}

I'm trying to update a record using the following:

let result = await vehicle_model.findOneAndUpdate({ _id: some_id, 'Vehicles.Id': some_other_id }, { 'Vehicles.Recycle': true });

The field Recycle may or may not be present. So if it's not, add it. If it is, update it.

But the it responds by returning a load of records (not just the one I'm wanting to update), and my app bombs with the error "PathNotViable'.

Any ideas please?

CodePudding user response:

In this particular case, you can achieve what you want using the positional $ operator as follows:

db.collection.update({
  _id: 123,
  "Vehicles.Id": "A"
},
{
  $set: {
    "Vehicles.$.Recycle": true
  }
})

Playground demonstration here.

If in the future you needed something a little bit more complex for your array manipulations, you could look into the following:

  • Related