title: How to define a sort function in Mongoose
body: <p>I'm developing a small NodeJS web app using Mongoose to access my MongoDB database. A simplified schema of my collection is given below:</p>
  
  <pre><code>var MySchema = mongoose.Schema({                                 
      content:   { type: String },     
      location:  {                                                        
           lat:      { type: Number },                       
           lng:      { type: Number },                                              
      },
      modifierValue:  { type: Number }     
  });
  </code></pre>
  
  <p>Unfortunately, I'm not able to sort the retrieved data from the server the way it is more convenient for me. I wish to sort my results according to their distance from a given position (<em>location</em>) but taking into account a modifier function with a <em>modifierValue</em> that is also considered as an input.</p>
  
  <p>What I intend to do is written below. However, this sort of sort functionality seems to not exist.</p>
  
  <pre><code>MySchema.find({})
          .sort( modifierFunction(location,this.location,this.modifierValue) )
          .limit(20)       // I only want the 20 "closest" documents
          .exec(callback)
  </code></pre>
  
  <p>The mondifierFunction returns a Double.</p>
  
  <p>So far, I've studied the possibility of using mongoose's $near function, but this doesn't seem to sort, not allow for a modifier function.</p>
  
  <p>Since I'm fairly new to node.js and mongoose, I may be taking a completely wrong approach to my problem, so I'm open to complete redesigns of my programming logic.</p>
  
  <p>Thank you in advance,</p>