【问题标题】:How to update existing object inside an array using mongoose如何使用猫鼬更新数组中的现有对象
【发布时间】:2021-01-12 08:19:34
【问题描述】:

我正在尝试使用我的 discord.js 机器人和猫鼬创建一个货币系统。这是一个示例 MongoDB 文档格式:

{
  guild: "2095843098435435435",
  wallets: [
    {
      id: "2323232335354",
      amount: 10,
    },
    {
      id: "24344343234454",
      amount: "i want to update this",
    },
  ],
};

据我所知,Array.prototype.push() 函数用于在数组中创建一个新对象。

但是如何更新数组中的现有对象呢?

我的代码:

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();
}

【问题讨论】:

    标签: node.js mongoose discord.js


    【解决方案1】:

    您可以使用$set 运算符来更新您的收藏,这样会有所帮助

    db.collection.update({"wallets.id": "24344343234454"},{$set: {
            "wallets.$.amount": "This is new_value"
        }}
    

    你可以阅读更多关于$set here的信息。

    $ 符号是位置运算符,它将保存在第一个表达式中匹配的数组项的位置(索引)。更多关于positional operator here

    【讨论】:

    • "This is new_value" 我的当前值设置为account.amount += args[3],但我现在不知道应该用帐户替换什么。应该是wallets.amount 还是find.wallets.amount
    • # 等等哥们,这是我正在使用的 mongoose,mongoose npm pack,而不是 mongodb
    猜你喜欢
    • 2021-12-28
    • 2020-07-31
    • 1970-01-01
    • 2019-09-14
    • 2015-01-13
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多