Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findOneAndUpdate with sort and limit

var query = Session
   .find({ player: player, logout: null })
   .sort({ 'login.date': -1 })
   .limit(1);

query.exec(function(err, data) {
  var session = new Session(data);
  session.logout = logoutEvent;
  session.save();
});

How can I convert this into findOneAndUpdate?

Here is an example of using findOneAndUpdate but im not sure how to add sort and limit:

var query = {'username':req.user.username};
req.newData.username = req.user.username;
MyModel.findOneAndUpdate(query, req.newData, {upsert:true}, function(err, doc){
    if (err) return res.send(500, { error: err });
    return res.send("succesfully saved");
});
like image 668
Jonathan Avatar asked Sep 14 '14 22:09

Jonathan


1 Answers

You can add sort to you options dict:

{ upsert: true, sort: { 'login.date': -1 } }
like image 93
Mattias Farnemyhr Avatar answered Sep 24 '22 09:09

Mattias Farnemyhr