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?