4

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?

2
  • 2
    id: userId or user: userId is this ok? because your query seems to be ok... Commented Jul 8, 2018 at 4:00
  • @AnthonyWinzlet thank you so much! "id" was indeed incorrect, the field was actually "user" as you suggested - it now works perfectly. If you'd like to add this as an answer, I'll choose it as the accepted answer. Commented Jul 8, 2018 at 22:27

2 Answers 2

3

I think you mismatched id and user field

Try to change id with user

SavedFoods.findOneAndUpdate(
    {
      user: userId,
      'list.id': 0
    }
)
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.