[英]Mongoose update map element inside array of document
如标题所示,我想使用Mongoose更新文档数组中的映射中的值Im。 这是针对Discord机器人的,基本上是每次用户执行命令时都会将exp添加到char中,并且它可以工作,但是看起来不正确,并且有人告诉我有时它不起作用:
这是数组内的映射的样子: 单击
// 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次)。
我发现这是可行的,即使它仍然可以将对象移动到地图的最后一个位置,但看起来也比我拥有的要干净:
await bot.userinventories.updateOne(
{ userID: message.author.id, "characters.name": check[0].name },
{ $set: { "characters.$.exp" : check[0].exp } }
)
编辑:为了不将编辑的对象移到最后一个位置,我不得不创建一个新变量,或者出于某种原因不对'“ characters。$。exp”:'使用变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.