How to define a sort function in Mongoose How to define a sort function in Mongoose mongoose mongoose

How to define a sort function in Mongoose


You might have found an answer to this already given the question date, but I'll answer anyway.

For more advanced sorting algorithms you can do the sorting in the exec callback. For example

MySchema.find({})  .limit(20)  .exec(function(err, instances) {      let sorted = mySort(instances); // Sorting here      // Boilerplate output that has nothing to do with the sorting.      let response = { };      if (err) {          response = handleError(err);      } else {          response.status = HttpStatus.OK;          response.message = sorted;      }      res.status(response.status).json(response.message);  })

mySort() has the found array from the query execution as input and the sorted array as output. It could for instance be something like this

function mySort (array) {  array.sort(function (a, b) {    let distanceA = Math.sqrt(a.location.lat**2 + a.location.lng**2);    let distanceB = Math.sqrt(b.location.lat**2 + b.location.lng**2);    if (distanceA < distanceB) {      return -1;    } else if (distanceA > distanceB) {      return 1;    } else {      return 0;    }  })  return array;}

This sorting algorithm is just an illustration of how sorting could be done. You would of course have to write the proper algorithm yourself. Remember that the result of the query is an array that you can manipulate as you want. array.sort() is your friend. You can information about it here.