簡體   English   中英

如何在Mongoose中定義排序函數

[英]How to define a sort function in Mongoose

我正在使用Mongoose開發一個小型NodeJS Web應用程序來訪問我的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)

mondifierFunction返回一個Double。

到目前為止,我已經研究了使用mongoose的$ near函數的可能性,但這似乎沒有排序,不允許修飾函數。

由於我對node.js和mongoose很新,我可能對我的問題采用了一種完全錯誤的方法,所以我願意完全重新設計我的編程邏輯。

先感謝您,

考慮到問題日期,您可能已經找到了答案,但無論如何我都會回答。

對於更高級的排序算法,您可以在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()是你的朋友。 您可以在此處獲取相關信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM