I'm going through the methods chapter of Your First Meteor Application by David Turnbull.
I have a method for updating a field in the database.
'modifyPlayerScore': function(selectedPlayer, scoreValue){
PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} });
}
and these methods are being called from event functions
'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);
}
When I use this functions in the app, I see an error in Terminal
Exception while invoking method 'modifyPlayerScore' MongoError: Modifier $inc allowed for numbers only
I have used a console.log statement to print the scoreValue variable and it shows either 5 or -5. I have a feeling that this may be a string and not a number but I'm not sure how to fix this error. Thanks in advance for your help!
When you added the score to a player with :
PlayersList.insert({name: 'test', score:3});
I suppose, you could increase the score. But not anymore.
It's because you passed a text parameter instead of an integer. When you add a player you should use parseInt():
PlayersList.insert({
name: name,
score: parseInt(score),
createdBy: Meteor.userId()
})
Now, it should work. Or you can use parseInt() to set score
You should change the Meteor.method
to this.
On the $inc
remove the 5
static and place the second argument (scoreValue
).
The method should look like this.
modifyPlayerScore': function(selectedPlayer, scoreValue){
PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} });
}
And now you can make the call like this.
Meteor.call('modifyPlayerScore', selectedPlayer, 5);
where 5 its now the scoreValue
argument
UPDATE
I made this working MeteorPad check you have everything like this.
NEW METEORPAD
I made this meteor pad based on the gist, and everything its working.
I used parse int on the score within PlayerList.insert as suggested above by yoh and it works for new entries. The old entries for score are still saved as strings so increment and decrement do not work. Delete your old entries and start fresh, it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With