猫鼬在文档数组中更新map元素

时间:2019-03-14 18:29:50

标签: javascript arrays mongodb mongoose

正如标题所说,我想使用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次一样随机失败。

1 个答案:

答案 0 :(得分:1)

我发现这是可行的,即使它仍然可以将对象移动到地图的最后一个位置,但看起来比我的还干净:

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

编辑:为使其不能将编辑后的对象移动到最后一位,我不得不创建一个新变量,或者出于某种原因不对'“ characters。$。exp”:'使用变量