Reputation: 103
Trying to add taxes to a user using 3 parameters of User, original, and percent. The schemas are defined below as well as the calling of the function
const usertaxschema = require('./schemas/usertaxschema')
const maintaxschema = require('./schemas/maintaxschema')
const taxedamount = ((percent/100)*original).toFixed(0)
const data = await usertaxschema.findOne({User:User})
if(!data) {
const newSchema = new usertaxschema({
User:User,
TaxesPaidInTotal:0,
TakesPaidThisPeriod:0,
})
await newSchema.save().catch((err) => console.log(err))
return 0
}
const chubster = await maintaxschema.findOne({Taxes:'Main'})
chubster.TotalTaxesPaid +=taxedamount
chubster.taxesavailable += taxedamount
data.TotalTaxesPaid +=taxedamount
data.TimePeriod += taxedamount
await chubster.save()
await data.save()
return taxedamount
}
UserTaxSchema
const mongoose = require('mongoose')
const usertaxschema = mongoose.Schema({
User:String,
TaxesPaidInTotal:Number,
TimePeriod:Number,
})
module.exports = mongoose.model('usertaxes', usertaxschema, 'usertaxes')
MainTaxSchema
const mongoose = require('mongoose')
const maintaxschema = mongoose.Schema({
Taxes:String, //Main etc
TotalTaxesAllTime:Number,
TaxesCollectedThisPeriod:Number,
TaxesInBalance:Number,
})
module.exports = mongoose.model('maintaxes', maintaxschema, 'maintaxes')
Example of calling function
const fatso = await Client.economy.taxUser(interaction.user.id, 500, 11.5)
console.log(fatso)
Upvotes: 0
Views: 36
Reputation: 6579
Number.toFixed
returns a String
. That's where "58"
comes from. Then you "add" (concatenate) the String
"58"
to various properties that should be storing numbers, but it seems that the property TimePeriod
is undefined
, so then it concatenates undefined
and "58"
and you get the value "undefined58"
.
You have to fix two things:
undefined
before you add to themTo solve #1, this line
const taxedamount = ((percent/100)*original).toFixed(0)
should use Math.round
instead of .toFixed
, because Math.round
returns a number, while .toFixed
returns a String.
const taxedamount = Math.round(percent / 100 * original)
To solve #2, you need to check for undefined
(maybe even for null
, if that's also a possible value) before you add values.
But are you sure you should be adding a "taxed amount" to a "time period"?
Well anyway, if that is what you want to do, and if you want to add the amount even if the current value of the property is undefined
(or null
) you can default to 0 before you add
data.TimePeriod = (data.TimePeriod || 0) + taxedamount
You should do that for all properties that can contain undefined
(or null
) in order to not get a NaN
(not a number) value.
Upvotes: 1