Node.js 如何通过Mongoose查询对嵌入文档数组进行排序?

Node.js 如何通过Mongoose查询对嵌入文档数组进行排序?,node.js,mongoose,Node.js,Mongoose,我正在用Mongoose构建一个node.js应用程序,在对嵌入文档进行排序时遇到了一个问题。以下是我使用的模式: var locationSchema = new Schema({ lat: { type: String, required: true }, lon: { type: String, required: true }, time: { type: Date, required: true }, acc: { type: String } })

我正在用Mongoose构建一个node.js应用程序,在对嵌入文档进行排序时遇到了一个问题。以下是我使用的模式:

var locationSchema = new Schema({
    lat: { type: String, required: true },
    lon: { type: String, required: true },
    time: { type: Date, required: true },
    acc: { type: String }
})

var locationsSchema = new Schema({
    userId: { type: ObjectId },
    source: { type: ObjectId, required: true },
    locations: [ locationSchema ]
});
我想输出嵌入在userLocations文档中的位置,这些位置按其时间属性排序。在从MongoDb检索到数据后,我目前使用JavaScript进行排序,如下所示:

function locationsDescendingTimeOrder(loc1, loc2) {
   return loc2.time.getTime() - loc1.time.getTime()
}

LocationsModel.findOne({ userId: theUserId }, function(err, userLocations) { 
   userLocations.locations.sort(locationsDescendingTimeOrder).forEach(function(location) {
      console.log('location: ' + location.time);
   }
});
我确实读过Mongoose提供的排序API,但我不知道它是否可以用于对嵌入式文档数组进行排序,如果可以,它是否是一种合理的方法,以及如何将其应用于此问题。有人能帮我吗

提前感谢,干杯,
乔治

你做得对,乔治。您的其他选择是在嵌入位置时按时间对位置进行排序,或者采用更传统的非嵌入路线(或者采用最小嵌入路线,这样您可以嵌入一个ID数组或其他东西,但实际上是单独查询位置)。

这也可以使用mongoose sort API完成

LocationsModel.findOne({userId:theUserId})
//.sort({“locations.time”:“desc”})//选项1
.sort(“-locations.time”)//选项2
.exec((错误,结果)=>{
//计算获取的数据
})

这个答案中还提到了更多的方法


谢谢你,杰德。我最终使用了您建议的方法——在嵌入时对位置进行排序。这对我来说很好。这也是我的问题,但如何在嵌入时对嵌入的文档进行排序?我已经解决了。您可能是指通过.push或.unshift添加新文档时,它将被正确定位。