如何在Mongoose中定义排序功能

pup*_*162 5 sorting mongoose mongodb node.js

我正在开发一个使用Mongoose访问我的MongoDB数据库的小型NodeJS Web应用程序。我的收藏的简化架构如下:

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

不幸的是,我无法以更方便的方式对从服务器检索到的数据进行排序。我希望根据结果与给定位置(location)的距离对结果进行排序,但要考虑到带有modifierValue的modifier函数,该modifierValue也被视为输入。

我打算做的写在下面。但是,这种排序功能似乎不存在。

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

mondifierFunction返回一个Double。

到目前为止,我已经研究了使用猫鼬的$ near函数的可能性,但是这似乎没有排序,不允许使用修饰符函数。

由于我对node.js和mongoose还是比较陌生,因此我可能会采用完全错误的方法来解决问题,因此我愿意完全重新设计我的编程逻辑。

先感谢您,

Mik*_*kaS 4

您可能已经在给出问题日期的情况下找到了答案,但无论如何我都会回答。

对于更高级的排序算法,您可以在 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);
  })
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

该排序算法只是如何进行排序的示例。您当然必须自己编写正确的算法。请记住,查询的结果是一个您可以根据需要进行操作的数组。array.sort()是你的朋友。您可以在这里了解相关信息。