NodeJS从mongo添加数字

NodeJS adding numbers from mongo

本文关键字:数字 添加 mongo NodeJS      更新时间:2023-09-26

我有这个基本的代码在express

var currpoints = user.points;
var addedpoints = req.body.points;
var newpoints = currpoints+addedpoints;
user.points = newpoints;

如果currentpoints = 10addedpoints = 100,则var newpoints返回10100。

我怎么能改变这个,使它添加10 + 100到110?

看起来JavaScript将这些值视为字符串。

你可以这样做:

var currpoints = parseInt(user.points, 10);
var addedpoints = parseInt(req.body.points, 10);
var newpoints = currpoints + addedpoints;

var currpoints = user.points;
var addedpoints = req.body.points;
var newpoints = parseInt(currpoints, 10) + parseInt(addedpoints, 10);

然后应该返回正确的数字,而不是将字符串连接在一起。