如何在Mongoose中定义一个sorting函数

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

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

不幸的是,我无法以更方便的方式从服务器中检索检索到的数据。 我希望根据它们与给定位置( 位置 )之间的距离对结果进行sorting,但是还要考虑修饰符函数和修饰符值,该修饰符值也被视为input。

我打算做的是写在下面。 但是,这种sortingfunction似乎不存在。

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

mondifierFunction返回Double。

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

由于我对node.js和mongoose相当陌生,因此我可能会对自己的问题采取完全错误的方法,所以我打开完成对我的编程逻辑的重新devise。

先谢谢你,

你可能已经find了答案,这已经给了问题的date,但我会回答。

对于更高级的sortingalgorithm,您可以在execcallback中进行sorting。 例如

 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()将查询执行中find的数组作为input,并将有序数组作为输出。 它可能是这样的事情

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

这种sortingalgorithm只是如何sorting的例子。 你当然必须自己写出适当的algorithm。 请记住,查询的结果是一个您可以随意操作的数组。 array.sort()是你的朋友。 你可以在这里了解它的信息 。