【问题标题】:Mongoose findOneAndUpdate: update an object in an array of objectsMongoose findOneAndUpdate:更新对象数组中的一个对象
【发布时间】:2018-12-16 00:23:02
【问题描述】:

我遇到了与此线程中描述的完全相同的问题(因此标题相似):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 设置为“其他”。

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)
    }
  )
}

回调被调用并且没有错误,但是更改没有反映在我的数据库中。

我做错了吗?

【问题讨论】:

  • id: userIduser: userId 可以吗?因为您的查询似乎没问题...
  • @AnthonyWinzlet 非常感谢! “id”确实不正确,正如您所建议的那样,该字段实际上是“用户” - 它现在可以完美运行。如果您想将此添加为答案,我会选择它作为接受的答案。

标签: mongodb mongoose


【解决方案1】:

我认为您的 iduser 字段不匹配

尝试将id更改为user

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)
        }
      )
    }
    

    为我工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2022-10-13
      • 2019-03-25
      • 2018-04-26
      • 2013-03-19
      • 1970-01-01
      相关资源
      最近更新 更多