[英]Find and update dynamic values MongoDB
I'm coding a Discord bot in java script right now.我现在正在java 脚本中编写Discord 机器人。 I use MongoDB to store a "heat" value for every user in my server.
我使用MongoDB为我的服务器中的每个用户存储“热量”值。 (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).
(每当用户做错事并在一段时间后再次取消时,“加热系统”会增加一定的百分比,更具体地说:在我的示例中每分钟 -5% )。
To do that, I want to use Model.updateMany()
in a loop.为此,我想在循环中使用
Model.updateMany()
。 As you see below, I used the filter parameter to find every document related to my server.正如您在下面看到的,我使用 filter 参数来查找与我的服务器相关的每个文档。 The question now is how I can take these 5% off the stored value because it's not static, but dynamic.
现在的问题是我如何才能从存储的价值中扣除这 5%,因为它不是 static,而是动态的。
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:还可以看看我的 model 是如何构建的:
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九头蛇
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.说明:-您希望每次减少 5% 的热量,然后您可以使用
mul
运算符并将您的热量值设置为当前值的 95%。 It will give you 5% deduction every time.每次都会给你5%的减免。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.