Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor methods and Mongo $inc non-number error

Tags:

mongodb

meteor

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!

like image 393
Anish Kothari Avatar asked Mar 03 '15 16:03

Anish Kothari


3 Answers

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

like image 63
yoh Avatar answered Oct 18 '22 17:10

yoh


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.

like image 33
Ethaan Avatar answered Oct 18 '22 17:10

Ethaan


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.

like image 1
shinySerenity Avatar answered Oct 18 '22 16:10

shinySerenity