流星方法和Mongo $ inc非数字错误

Ani*_*ari 5 mongodb meteor

我正在研究 David Turnbull撰写的“ 您的第一颗流星应用程序”方法一章。

我有一种更新数据库中字段的方法。

'modifyPlayerScore': function(selectedPlayer, scoreValue){ PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} }); }

这些方法是从事件函数中调用的

'click .increment': function(){

    var selectedPlayer = Session.get('selectedPlayer');

    Meteor.call('modifyPlayerScore', selectedPlayer, 5);

 },
 'click .decrement': function(){

    var selectedPlayer = Session.get('selectedPlayer');

    Meteor.call('modifyPlayerScore', selectedPlayer, -5);

  }
Run Code Online (Sandbox Code Playgroud)

当我在应用程序中使用此功能时,在终端中看到错误

Exception while invoking method 'modifyPlayerScore' MongoError: Modifier $inc allowed for numbers only
Run Code Online (Sandbox Code Playgroud)

我已经使用console.log语句来打印scoreValue变量,它显示5或-5。我感觉这可能是字符串而不是数字,但是我不确定如何解决此错误。在此先感谢您的帮助!

小智 4

当您使用以下命令将分数添加到玩家时:

PlayersList.insert({name: 'test', score:3});
Run Code Online (Sandbox Code Playgroud)

我想,你可以提高分数。但现在不再了。

这是因为您传递了文本参数而不是整数。当你添加一个玩家时,你应该使用parseInt():

 PlayersList.insert({
  name: name,
  score: parseInt(score),
  createdBy: Meteor.userId()
})
Run Code Online (Sandbox Code Playgroud)

现在,它应该可以工作了。或者您可以使用 parseInt() 来设置score