Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findOneAndUpdate: update an object in an array of objects

I have the exact same issue as described in this thread (hence the similar title): Mongoose findOneAndUpdate -- updating an object inside an array of objects

Given this model:

const SavedFoodsSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: 'User' },
  list: [
    {
      id: { type: Number, required: true, unique: true },
      name: { type: String, required: true },
      points: { type: Number, required: true }
    }
  ]
})

I wrote the following function just to test finding a document in the SavedFoods Collection based on the userId param, and then in the list array, for the first object in the array, setting the name to "Something else".

function updateFood (userId) {
  // This didn't work
  SavedFoods.findOneAndUpdate(
    {
      id: userId,
      'list.id': 0
    },
    {
      $set: {
        'list.$.name': 'Something else'
      }
    },
    null,
    (err) => {
      if (err) {
        console.log('Error:', err)
      } else {
        console.log('Updated', userId)
      }
      process.exit(0)
    }
  )
}

The callback is called and there is no error, however the the changes do not get reflected in my db.

Am I doing something wrong?

like image 803
Liran H Avatar asked Sep 17 '25 10:09

Liran H


2 Answers

I think you mismatched id and user field

Try to change id with user

SavedFoods.findOneAndUpdate(
    {
      user: userId,
      'list.id': 0
    }
)
like image 96
Ashh Avatar answered Sep 19 '25 05:09

Ashh


I had the same problem, so I just delete $set from .findOneAndUpdate

Example:

function updateFood (userId) {
  SavedFoods.findOneAndUpdate(
    {
      id: userId,
      'list.id': 0
    },
    {
      {'list.$.name': 'Something else'}
    },
    null,
    (err) => {
      if (err) {
        console.log('Error:', err)
      } else {
        console.log('Updated', userId)
      }
      process.exit(0)
    }
  )
}

Works for me.

like image 20
TryToSayMyNICK Avatar answered Sep 19 '25 07:09

TryToSayMyNICK