Mongoose findOneAndUpdate:更新对象数组中的对象

4
我有和这个帖子描述的完全相同的问题(因此标题类似):Mongoose findOneAndUpdate -- updating an object inside an array of objects 给定这个模型:
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)
    }
  )
}

回调函数被调用并且没有错误,但是我的数据库中没有反映出更改。我做错了什么吗?

2
“id: userId”或“user: userId”可以吗?因为您的查询似乎没问题… - Ashh
@AnthonyWinzlet非常感谢!“id”确实不正确,字段实际上是“user”,正如您所建议的那样 - 现在它完美地工作了。如果您想将其添加为答案,我将选择它作为接受的答案。 - Liran H
2个回答

3

我认为你混淆了 id user 字段

尝试用用户替换 id

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

2
我也遇到了同样的问题,所以我只是从 .findOneAndUpdate 中删除了 $set
示例:
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)
    }
  )
}

对我来说没问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接