如何使用猫鼬更新数组中的现有对象 [英] How to update existing object inside an array using mongoose
问题描述
我正在尝试使用我的 discord.js 机器人和猫鼬创建一个货币系统.这是一个示例 MongoDB 文档格式:
I'm trying to make a currency system with my discord.js bot and mongoose. Here is an example MongoDB document format:
{
guild: "2095843098435435435",
wallets: [
{
id: "2323232335354",
amount: 10,
},
{
id: "24344343234454",
amount: "i want to update this",
},
],
};
据我所知,Array.prototype.push()
函数用于在数组中创建一个新对象.
As far as I know, the Array.prototype.push()
function is for making a new object inside an array.
但是如何更新数组中的现有对象呢?
But how can I update an existing object inside an array?
我的代码:
const find = await Account.findOne({
guild: message.guild.id,
});
if (!find) return message.channel.send("...");
const memberRole = message.guild.members.cache
.find((x) => x.id === message.author.id)
.roles.cache.find(
(x) =>
x.name.toLowerCase() === "tournament manager" ||
x.name.toLowerCase() === "events staff" ||
x.name.toLowerCase() === "wallet manager"
);
if (message.member.hasPermission("ADMINISTRATOR") || memberRole) {
if (!args[2]) return message.reply("...");
const mention = message.mentions.users.first();
if (!mention) return message.reply("...");
const account = find.wallets.find((x) => x.id === mention.id);
if (!account) return message.reply("...");
if (!args[3]) return message.reply("...");
if (isNaN(args[3])) return message.channel.send("...");
const update = account.update({
amount: (account.amount += args[3]),
});
await find.save();
}
推荐答案
您可以使用 $set
运算符来更新您的集合,这样会有所帮助
You can use $set
Operator to update your collection something like this will help
db.collection.update({"wallets.id": "24344343234454"},{$set: {
"wallets.$.amount": "This is new_value"
}}
您可以在 $set 此处阅读更多信息.
$
符号是位置运算符,它将保存在第一个表达式中匹配的数组项的位置(索引).更多关于位置运算符在这里.
The $
sign is the positional operator that will hold the position(index) of array item matched in first expression. More about positional operator here.
这篇关于如何使用猫鼬更新数组中的现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!