查找和更新动态值 MongoDB

Find and update dynamic values MongoDB

我现在正在 java 脚本 中编写 Discord bot。我使用 MongoDB 为服务器中的每个用户存储一个“热度”值。 (每当用户做错事并在一段时间后再次将其删除时,“热系统”会增加一定的百分比,更具体地说:每分钟 -5%我的例子)。

为此,我想在循环中使用 Model.updateMany()。正如您在下面看到的,我使用过滤器参数来查找与我的服务器相关的每个文档。现在的问题是我怎样才能从存储的价值中扣除这 5%,因为它不是静态的,而是动态的。

    const { Client } = require('discord.js');
    const mongoose = require('mongoose');
    //using modules and event handlers
    module.exports = {
        name: 'ready',
        /**
         * @param {Client} client
         */
        async execute(client) {
            const heatdb = require('/app/models/heatDB.js');
            //how often the loop should pe repeated
            const interval = 10 * 60 * 1000;
            console.log('Client ready.')
            //connnecting my data
            mongoose.connect(
                'I put the mongoose link here', {
                    useNewUrlParser: true,
                    useUnifiedTopology: true
            }).then(() => {
                console.log('Data connected.')
            }).catch((err) => {
                console.log(err)
            });
            //loop begins here
            setInterval(function(){
                //filtered so that it's only searching for documents having the guild ID in it
                heatdb.updateMany({ GuildID: "000000000000000000"}, {Heat: parseInt(/*needed value*/) - 5}})
            }, interval);
        },
    };

并在下面查看我的模型是如何构建的:

    const { Schema, model } = require('mongoose');

    module.exports = model("heatDB", new Schema({
        GuildID: String,
        UserID: String,
        Heat: String,
    }))

如果您需要任何其他帮助,请告诉我。

提前致谢,

九头蛇

如果你的 Heat 值是模式中的数字而不是字符串,那么你可以试试这个-

heatdb.updateMany({ GuildID: "000000000000000000"},{$mul:{"Heat":0.95}})

解释:- 你想每次减少 5% 的热量然后你可以使用 mul 操作员 & 将您的热值设置为当前值的 95%。每次都会给你5%的折扣。