猫鼬findOneAndUpdate:更新对象数组中的对象 [英] Mongoose findOneAndUpdate: update an object in an array of objects

查看:77
本文介绍了猫鼬findOneAndUpdate:更新对象数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有与该线程中所述完全相同的问题(因此具有类似的标题):

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

给出此模型:

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设置为其他.

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.

我做错什么了吗?

推荐答案

我认为您不匹配iduser字段

尝试用user

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

这篇关于猫鼬findOneAndUpdate:更新对象数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆