PlexHydra
PlexHydra

Reputation: 3

Find and update dynamic values MongoDB

I'm coding a Discord bot in java script right now. I use MongoDB to store a "heat" value for every user in my server. (The "heat-system" adds a certain amount to a percentage whenever the user does something wrong and takes it off again after some time, to be more specific: -5 percent every minute in my example).

To do that, I want to use Model.updateMany() in a loop. As you see below, I used the filter parameter to find every document related to my server. The question now is how I can take these 5% off the stored value because it's not static, but dynamic.

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

And also see how my model is built below:

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

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

If you need anything else to help me, please let me know.

Thank you in advance,

Hydra

Upvotes: 0

Views: 148

Answers (1)

Gulshan Aggarwal
Gulshan Aggarwal

Reputation: 999

If your Heat value is a Number in Schema instead of String then you can try this-

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

Explanation:- you want to reduce Heat every time 5% percent then you can use mul operator & set your heat value to 95% of current value. It will give you 5% deduction every time.

Upvotes: 1

Related Questions