简体   繁体   English

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

[英]Mongoose update map element inside array of document

as the title says, I want to update a value in a map inside an array in a document, Im using Mongoose. 如标题所示,我想使用Mongoose更新文档数组中的映射中的值Im。 This is for a Discord bot, basically adding exp to a char every time user does a command, and it works, but it doesn't look right and I've been told it doesn't work sometimes: 这是针对Discord机器人的,基本上是每次用户执行命令时都会将exp添加到char中,并且它可以工作,但是看起来不正确,并且有人告诉我有时它不起作用:

This is how the maps inside the array look like: 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]
                    }
            })

As you can see, the part that doesn't seem right is having to entirely remove the map before saving it again, this also breaks any order by date. 如您所见,看起来不正确的部分是必须再次完全保存地图才能再次保存它,这也会破坏按日期排列的任何顺序。 The big problem is that users have told me they've lost characters to this. 最大的问题是用户告诉我他们已经失去了角色。 Another thing that sometimes fails is the 'let check' line, even tho it finds a map by the exact name (because of my code) it fails randomly like 1/20 times. 有时会失败的另一件事是“让支票”行,即使它以确切的名称(由于我的代码)找到了地图,它也会随机失败(如1/20次)。

I found this which works, even tho it stills moves the object to the last place of the map, but it seems cleaner than what I had: 我发现这是可行的,即使它仍然可以将对象移动到地图的最后一个位置,但看起来也比我拥有的要干净:

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

Edit: for it to not move the edited object to last place, I had to make a new variable or not use a variable for '"characters.$.exp" : ' for some reason 编辑:为了不将编辑的对象移到最后一个位置,我不得不创建一个新变量,或者出于某种原因不对'“ characters。$。exp”:'使用变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM