-1

i am making A Discord.js Add-money command but its having a Wierd bug, Whever i execute this command ?add-money 1 then it perfectly works fine but when i execute it again by typing ?add-money 1 then instead of it to make my balance to 2 it makes it to 11 which literally makes no Sense, please help with my problem.

here is the code:

const { MessageEmbed, MessageButton, MessageActionRow } = require(`discord.js`);
const ee = require(`../../botconfig/embed.json`);
const User = require("../../models/user.js")
module.exports = {
    name: `add-money`,
    run: async (client, message, args) => {
       if(!message.member.permissions.has("ADMINISTRATOR") return message.channel.send("You Dont Have Required Perms to Run This Command!")
        let user = await User.findOne({ id: message.author.id })
        if(!user) return message.channel.send(`You Dont own a Account yet!`)
        let amount = args[0]
          if(Number.isNaN(+amount)) return message.channel.send(`The amount is Not A Number!`)
          user.coins = user.coins + amount
          await user.save()
          return message.channel.send(`You added ${amount} to your balance!`)
    }
}

Here is My Mongoose Model:

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
    id: { type: String, required: true },
    coins: { type: Number, default: 0 },
});

module.exports = mongoose.model("User", UserSchema);
Zsolt Meszaros
  • 15,542
  • 12
  • 36
  • 40
  • It makes perfect sense in JavaScript. `amount` is a string, and in JS the `+` operator concatenates strings (`1+"1"` is equal to `"11"`). You need to convert `amount` to a number. It's interesting that you already converted it to a number here to check if it's `NaN`: `isNaN(+amount)` – Zsolt Meszaros Mar 12 '22 at 09:24
  • Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – Zsolt Meszaros Mar 12 '22 at 09:27

1 Answers1

-1
user.coins += Math.floor(amount)
await user.save();
WOLF
  • 75
  • 5