Liran H
Liran H

Reputation: 10609

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?

Upvotes: 4

Views: 16989

Answers (2)

TryToSayMyNICK
TryToSayMyNICK

Reputation: 41

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.

Upvotes: 3

Ashh
Ashh

Reputation: 46491

I think you mismatched id and user field

Try to change id with user

SavedFoods.findOneAndUpdate(
    {
      user: userId,
      'list.id': 0
    }
)

Upvotes: 3

Related Questions