【问题标题】:Mongoose update map element inside array of document文档数组内的猫鼬更新地图元素
【发布时间】:2019-08-05 18:31:43
【问题描述】:

正如标题所说,我想在文档中的数组内更新地图中的值,我使用的是 Mongoose。这是针对 Discord 机器人的,基本上每次用户执行命令时都会将 exp 添加到 char 中,它可以工作,但它看起来不正确,有人告诉我它有时不起作用:

数组中的地图如下所示: click

// This gets the user document
let user = bot.userinventories.findOne({ userID: message.author.id })
// This searches the specific map I need by name
let check = await user.get('characters').filter(char => char.name === user.get('leveling'));

        // This modifies the map in only 1 value
        check[0].exp++;
        // This removes the entire map and saves it again
        await bot.userinventories.updateOne({ userID: message.author.id }, 
            { $pull: 
                { 
                characters:  { name: check[0].name }
                }
            })
        await bot.userinventories.updateOne({ userID: message.author.id }, 
                { $push: 
                    { 
                        characters: check[0]
                    }
            })

如您所见,似乎不正确的部分是必须在再次保存之前完全删除地图,这也会破坏任何按日期排列的顺序。最大的问题是用户告诉我他们已经为此丢失了字符。 有时会失败的另一件事是“让检查”行,即使它找到了确切名称的地图(因为我的代码),它也会随机失败 1/20 次。

【问题讨论】:

    标签: javascript arrays mongodb mongoose


    【解决方案1】:

    我发现这个可行,即使它仍然将对象移动到地图的最后一个位置,但它似乎比我所拥有的更干净:

    await bot.userinventories.updateOne(
                { userID: message.author.id, "characters.name": check[0].name },
                { $set: { "characters.$.exp" : check[0].exp } }
            )
    

    编辑:为了不将已编辑的对象移动到最后一个位置,我必须创建一个新变量或不使用变量 '"characters.$.exp" : ' 出于某种原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 2020-10-22
      • 2018-08-11
      • 2020-08-05
      • 2015-06-03
      • 2012-02-15
      • 2015-04-21
      • 2021-06-30
      相关资源
      最近更新 更多