如何使用猫鼬更新数组内的现有对象 [英] How to update existing object inside an array using mongoose

查看:64
本文介绍了如何使用猫鼬更新数组内的现有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的 discord.js bot 和 mongoose 创建一个货币系统.这是一个示例 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 此处的更多信息.

You can read more about $set here.

$ 符号是位置运算符,它将保存在第一个表达式中匹配的数组项的位置(索引).有关位置运算符的更多信息.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆