0

I have successfully got the one of the users with the lowest referrals using the node native driver

users.find().sort({referrals:1}).limit(1).toArray(function(error,result){
    console.log(error||result);
    });

^ this works fine

v this and other variations I have tried don't

When I want to make the function better by findAndModify I fail over and over (this is the closest I Think I have got from the docs)

users.findAndModify({},{referrals:1},{$inc:{referrals:1}},{}).toArray(function(error,result){                                                          
    console.log(error||result);
    });

I want to get one of the users with the lowest referrals and ++1 his referrals when I find him

Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32
Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66

2 Answers2

1

Try to do it with this query:

db.users.findAndModify({
    sort: {referrals:1}, 
    update: {$inc: {referrals:1}}, 
    new: true
}, callback)

Here you can see all possible parameters for findAndModify.

Community
  • 1
  • 1
Volodymyr Synytskyi
  • 3,885
  • 1
  • 15
  • 19
0

For those who might also be using the node native driver:

Based on this answer https://stackoverflow.com/a/24326067/990434

The .findAndModify() method in the node native driver implementation is different from the mongo shell implementation. The main difference being you do not name the "key" sections for the actions.

So in this case the code would be:

db.users.findAndModify(
     {}//query
    ,{referrals:1}//sort
    ,{$inc:{referrals:1}}//update
    ,{new:true}
    ,function(error,result){});
Community
  • 1
  • 1
Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66