我有和这个帖子描述的完全相同的问题(因此标题类似):Mongoose findOneAndUpdate -- updating an object inside an array of objects
给定这个模型:
我编写了以下函数仅用于测试根据userId参数在SavedFoods集合中查找文档,然后在list数组中将第一个对象的name设置为“Something else”。
回调函数被调用并且没有错误,但是我的数据库中没有反映出更改。我做错了什么吗?
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 }
}
]
})
我编写了以下函数仅用于测试根据userId参数在SavedFoods集合中查找文档,然后在list数组中将第一个对象的name设置为“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)
}
)
}
回调函数被调用并且没有错误,但是我的数据库中没有反映出更改。我做错了什么吗?