MongooseJS – How to find the element with the maximum value?

Member
  .findOne({ country_id: 10 })
  .sort('-score')  // give me the max
  .exec(function (err, member) {

    // your callback code

  });

Check the mongoose docs for querying, they are pretty good.

If you dont’t want to write the same code again you could also add a static method to your Member model like this:

memberSchema.statics.findMax = function (callback) {

  this.findOne({ country_id: 10 }) // 'this' now refers to the Member class
    .sort('-score')
    .exec(callback);
}

And call it later via Member.findMax(callback)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)