【问题标题】:Discord.JS/Mongoose Error: UnhandledPromiseRejectionWarning: CastError: Cast to Number failed for value "NaN" at path "cashBalance"Discord.JS/Mongoose 错误:UnhandledPromiseRejectionWarning:CastError:CashBalance 路径中值“NaN”的数字转换失败
【发布时间】:2021-05-07 19:08:31
【问题描述】:

我正在为我的 discord 机器人制作一个经济系统,你们中的一些人是来(尝试)解决猫鼬问题的,所以你不必太担心。

我正在执行“存款”命令,它会从您的余额中取出一定数量的现金并将其存入您的“银行”。

我将现金金额存入银行的部分有效,但我从余额中减去现金金额的部分(使您看起来像是从现金余额中取出钱)无效。我得到这个错误。 UnhandledPromiseRejectionWarning: CastError: Cast to Number failed for value "NaN" at path "cashBalance"

代码(与此错误有关):

if (!isNaN(parseInt(args[0]))) {
  console.log('is a num')

  await depositModel.updateOne({ bankBalance: parseInt(args[0]) }).then(async () => {
    await depositModel.updateOne({ cashBalance: depositModel.cashBalance - parseInt(args[0]) })
  })

  const embed = new Discord.MessageEmbed()
    .setColor('GREEN')
    .setDescription(`Successfully deposited ${parseInt(args[0])} to your bank!`)
    .setAuthor(message.author.username, message.author.displayAvatarURL())
    .setTimestamp()
  return message.channel.send(embed); 
} else {
  console.log('not num')
}

【问题讨论】:

  • 在您的模型中,cashBalance 是什么?
  • @Pentium1080Ti 基本上是你的现金余额,假设你从工作中赚了 500 美元,那将自动成为你的现金余额。它也是一个数字

标签: javascript node.js mongodb mongoose discord.js


【解决方案1】:

您不使用$inc operator 来更新您的字段的任何原因?您的代码中不需要所有的 async-await 和 .then()

const amount = parseInt(args[0]);

if (isNaN(amount)) {
  console.log('not num');
  return;
}

await depositModel.updateOne({
  $inc: {
    bankBalance: amount,
    cashBalance: amount * -1,
  },
});

const embed = new Discord.MessageEmbed()
  .setColor('GREEN')
  .setDescription(`Successfully deposited ${amount} to your bank!`)
  .setAuthor(message.author.username, message.author.displayAvatarURL())
  .setTimestamp();
  
return message.channel.send(embed);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-23
    • 2018-10-21
    • 2019-09-04
    • 2018-07-12
    • 2017-03-26
    • 2020-04-18
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多