【问题标题】:Discord.js/Mongodb How to update all database valuesDiscord.js/Mongodb 如何更新所有数据库值
【发布时间】:2021-08-07 03:15:03
【问题描述】:

我目前正在为 Discord 创建一个经济机器人,但我有一个问题我不知道如何解决:

所有用户都有薪水,这将通过命令设置。我想创建一个可以使用设置的工资金额更新所有用户帐户的命令。 我怎样才能让命令更新 MongoDB 数据库中所有找到的用户的值,而不是 ping 特定用户?

这是当前代码:

const profileModel = require("../models/profileSchema");
module.exports = {
    name: 'pay',
    aliases: [],
    permissions: ["ADMINISTRATOR"],
    description: "pay users their salary",
    async execute(message, args, cmd, client, discord, profileData) {
        const amount = profileData.pay;
        const target = message.mentions.users.first();

    try{

        await profileModel.findOneAndUpdate({
                userID: target.id,
        }, {
            $inc: {
                bank: amount,
            },
        }
        );

        return message.channel.send(`Users have been paid.`);
  } catch(err) {
      console.log(err);
  }
},
};

如您所见,目前它正在等待用户 ping 用户。但我希望它只更新数据库中所有找到的用户,而不需要指定它是谁。

我真的很想得到帮助!

【问题讨论】:

    标签: mongodb discord.js robo3t


    【解决方案1】:

    Mongo 有方法 updateMany, docs found here,如果查询设置为空对象,它会更新所有文档。所以,试试吧:

    await profileModel.updateMany({}, {
                $inc: {
                    bank: amount,
                },
            }
            );
    

    【讨论】:

    • 感谢您的回答。它几乎解决了我的问题。剩下的唯一问题是,它以相同的数量更新所有用户。第 1 个人有一个有 3000 个硬币的帐户。他的设定工资是 ​​3000。人 2 有一个账户,有 3000 个硬币。他的设定工资是 ​​2500。当我运行命令“pay”时,它会将两个帐户更新为 3000,而第 2 个人实际上应该收到 2500。那么我如何指定它来检查每个人自己设定的工资金额?
    猜你喜欢
    • 2020-12-08
    • 2022-10-09
    • 2012-04-27
    • 1970-01-01
    • 2022-01-26
    • 2016-12-31
    • 2022-08-20
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多