【问题标题】:How to increment a value which is in an object which is in an array which is in another object如何增加一个对象中的值,该对象位于另一个对象中的数组中
【发布时间】:2022-01-07 18:00:58
【问题描述】:

所以我正在尝试在 discord.js 中编写一个机器人,你基本上在库存中有物品,当我使用物品时,它的耐用性会下降。我正在使用 MongoDB Atlas 来存储所有数据。库存的结构是:

user: {
  id: 'user-id',
  name: 'user-name',
  inventory: [
    {
      name: 'item',
      durability: 5
    ,
    {
      name: 'another-item',
      durability: 20
    }
  ]
}

所以我只是想找到一种方法,基本上只是减少物品的耐久度,而不更新库存数组中的任何其他物品,但我无法找到方法。

【问题讨论】:

    标签: javascript mongodb mongoose discord.js


    【解决方案1】:

    您可以使用arrayFilters 仅更新您想要的值。

    您也可以使用$inc 来增加值(在这种情况下增加-1,即减少)

    db.collection.update({
      "id": "user-id"
    },
    {
      "$inc": {
        "inventory.$[element].durability": -1
      }
    },
    {
      "arrayFilters": [
        {
          "element.name": "item" //here use the name of the object you want to update
        }
      ]
    })
    

    例如here

    【讨论】:

    • 是的,等等,我明白了。出现错误是因为我使用的是findOneAndUpdate,而不是updateOne。感谢您的回答,现在可以使用了!
    【解决方案2】:

    我认为它有效,但弹出一个新错误:MongooseError: Callback must be a function, got [object Object]。我在 Google 中检查了这个错误,人们说这是由于根据 this => MongooseError: Callback must be a function, got [object Object] 的语法错误造成的。我的代码是这样的:

    const updatedUserData = await profileSchema.findOneAndUpdate({
        userId: interaction.user.id
    }, {
        "$inc": {
            "inventory.$[element].number": 1
        }
    
    }, {
        "arrayFilters": [
            {
                "element.id": "stone"
            }
        ]
    }, {
        upsert: true
    })

    但是当我像这样将 arrayFilters 移动到 $inc 对象中时:

    const updatedUserData = await profileSchema.findOneAndUpdate({
       userId: interaction.user.id
    }, {
       "$inc": {
           "inventory.$[element].number": 1
        },
        "arrayFilters": [
           {
               "element.id": "stone"
           }
       ]
    }, {
        upsert: true
    })

    出现了一个新错误,提示 MongoServerError: No array filter found for identifier 'element' in path 'inventory.$[element].number'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 2018-10-04
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      相关资源
      最近更新 更多