How to update existing object inside an array using mongoose

依然范特西╮ 提交于 2021-01-29 05:49:41

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/64073562/how-to-update-existing-object-inside-an-array-using-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!