流星方法和 Mongo $inc 非数字错误
Meteor methods and Mongo $inc non-number error
我正在阅读 David Turnbull 的你的第一个 Meteor 应用程序 的 methods 章。
我有一种方法可以更新数据库中的字段。
'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);
}
当我在应用程序中使用此功能时,我在终端中看到一个错误
Exception while invoking method 'modifyPlayerScore' MongoError: Modifier $inc allowed for numbers only
我使用了 console.log 语句来打印 scoreValue 变量,它显示 5 或 -5。我觉得这可能是一个字符串而不是一个数字,但我不确定如何解决这个错误。预先感谢您的帮助!
你应该把 Meteor.method
改成这个。
在 $inc
上删除 5
静态并放置第二个参数 (scoreValue
)。
该方法应如下所示。
modifyPlayerScore': function(selectedPlayer, scoreValue){
PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} });
}
现在你可以这样打电话了。
Meteor.call('modifyPlayerScore', selectedPlayer, 5);
其中 5 现在是 scoreValue
参数
更新
我this working MeteorPad检查你有这样的一切。
新的 METEORPAD
我制作了 this meteor pad based on the gist,一切正常。
当您将分数添加到玩家时:
PlayersList.insert({name: 'test', score:3});
我想,你可以提高分数。但现在不是了。
这是因为您传递的是文本参数而不是整数。
添加播放器时,您应该使用 parseInt():
PlayersList.insert({
name: name,
score: parseInt(score),
createdBy: Meteor.userId()
})
现在,它应该可以工作了。或者你可以使用 parseInt() 来设置 score
我按照 yoh 上面的建议在 PlayerList.insert 中对分数使用了 parse int,它适用于新条目。分数的旧条目仍保存为字符串,因此递增和递减不起作用。删除旧条目并重新开始,应该可以。
我正在阅读 David Turnbull 的你的第一个 Meteor 应用程序 的 methods 章。
我有一种方法可以更新数据库中的字段。
'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);
}
当我在应用程序中使用此功能时,我在终端中看到一个错误
Exception while invoking method 'modifyPlayerScore' MongoError: Modifier $inc allowed for numbers only
我使用了 console.log 语句来打印 scoreValue 变量,它显示 5 或 -5。我觉得这可能是一个字符串而不是一个数字,但我不确定如何解决这个错误。预先感谢您的帮助!
你应该把 Meteor.method
改成这个。
在 $inc
上删除 5
静态并放置第二个参数 (scoreValue
)。
该方法应如下所示。
modifyPlayerScore': function(selectedPlayer, scoreValue){
PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} });
}
现在你可以这样打电话了。
Meteor.call('modifyPlayerScore', selectedPlayer, 5);
其中 5 现在是 scoreValue
参数
更新
我this working MeteorPad检查你有这样的一切。
新的 METEORPAD
我制作了 this meteor pad based on the gist,一切正常。
当您将分数添加到玩家时:
PlayersList.insert({name: 'test', score:3});
我想,你可以提高分数。但现在不是了。
这是因为您传递的是文本参数而不是整数。 添加播放器时,您应该使用 parseInt():
PlayersList.insert({
name: name,
score: parseInt(score),
createdBy: Meteor.userId()
})
现在,它应该可以工作了。或者你可以使用 parseInt() 来设置 score
我按照 yoh 上面的建议在 PlayerList.insert 中对分数使用了 parse int,它适用于新条目。分数的旧条目仍保存为字符串,因此递增和递减不起作用。删除旧条目并重新开始,应该可以。