【问题标题】:How to define a sort function in Mongoose如何在 Mongoose 中定义排序函数
【发布时间】:2017-05-18 03:28:19
【问题描述】:

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

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

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

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

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

mondifierFunction 返回一个 Double。

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

由于我对 node.js 和 mongoose 还很陌生,我可能对我的问题采取了完全错误的方法,所以我愿意重新设计我的编程逻辑。

提前谢谢你,

【问题讨论】:

    标签: node.js mongodb sorting mongoose


    【解决方案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() 是你的朋友。您可以在here了解它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2013-03-13
      • 1970-01-01
      • 2017-09-13
      • 2021-08-04
      • 2012-02-16
      • 1970-01-01
      相关资源
      最近更新 更多