简体   繁体   中英

How to update existing object inside an array using mongoose

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",
    },
  ],
};

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?

My code:

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

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"
    }}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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