如何在Mongoose中定义排序函数

7

我正在开发一个小型的NodeJS Web应用程序,使用Mongoose来访问我的MongoDB数据库。下面是我的集合的简化模式:

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

很遗憾,我无法按照更方便我的方式对从服务器检索到的数据进行排序。我希望能根据它们与给定位置(位置)的距离来排序我的结果,但同时考虑一个修饰函数和一个modifierValue作为输入。

我打算做的事情写在下面。然而,这种排序功能似乎不存在。

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

modifierFunction返回一个Double类型的值。

到目前为止,我已经研究过使用mongoose的$near函数的可能性了,但是它似乎不能排序,也不允许使用修改器函数。

由于我对node.js和mongoose还比较新,所以我可能在解决问题时采取了完全错误的方法,因此我很乐意重新设计我的编程逻辑。

提前感谢您的帮助。

1个回答

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

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() 是您的好朋友。您可以在这里获取有关它的信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接