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?
I think you mismatched id and user field
Try to change id with user
SavedFoods.findOneAndUpdate(
    {
      user: userId,
      'list.id': 0
    }
)
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With