【发布时间】:2012-03-10 02:15:46
【问题描述】:
我正在使用 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,但我不知道它是否可用于对嵌入式文档数组进行排序,如果可以,它是否是一种明智的方法以及如何将其应用于此问题。谁能帮帮我好吗?
在此先感谢和欢呼, 乔治
【问题讨论】: