'How to update an existing object using Mongoose?
So I'm trying to make a command (/performance add) that adds points to the target user.
Basically if the command is /performance add Someone#0000 5 then it'll get the targeted user's points and add 5 to them.
So, Before command:
User: Someone#0000
Points: 0
After command:
User: Someone#0000
Points: 5
Code:
const db = require('../../Models/PointsDB');
db.findOne({ GuildID: interaction.guildId, UserID: Target.id }, async (err, data) => {
if (err) throw err;
if (!data) {
data = new db({
GuildID: interaction.guildId,
UserID: Target.id,
Points: PointsGiven
});
} else {
// That's where I'm struggling
}
data.save()
});
Thanks in advance
Solution 1:[1]
You can simply get the data then add on the number provided.
Example:
const db = require('../../Models/PointsDB');
db.findOne({ GuildID: interaction.guildId, UserID: Target.id }, async (err, data) => {
if (err) throw err;
if (!data) {
data = new db({
GuildID: interaction.guildId,
UserID: Target.id,
Points: PointsGiven
});
} else {
// Find the current amount of points then add on the provided amount of points
// The parseInt function converts a string to an integer value
data.Points = parseInt(data.Points) + parseInt(PointsGiven)
}
data.save()
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tyler2P |
