How to define a sort function in Mongoose

I am developing a small NodeJS web application using Mongoose to access my MongoDB database. The following is a simplified diagram of my collection:

var MySchema = mongoose.Schema({                                 
    content:   { type: String },     
    location:  {                                                        
         lat:      { type: Number },                       
         lng:      { type: Number },                                              
    },
    modifierValue:  { type: Number }     
});

Unfortunately, I cannot sort the received data from the server in a way that is more convenient for me. I want to sort the results according to their distance from a given position (location), but taking into account the modifier function with the Value modifier, which is also considered as an input.

What I intend to do is written below. However, this sorting function does not seem to exist.

MySchema.find({})
        .sort( modifierFunction(location,this.location,this.modifierValue) )
        .limit(20)       // I only want the 20 "closest" documents
        .exec(callback)

The mondifier function returns Double.

So far I have been exploring the possibility of using the mongoose $ near function, but this does not seem to sort, the modifier does not allow.

node.js mongoose, , .

,

+4
1

, , .

exec.

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() . , , -

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;
}

, . , . , , . array.sort() - . .

+1

Source: https://habr.com/ru/post/1665664/


All Articles