3
我使用Mongoose构建了一个node.js应用程序,并且遇到了有关排序嵌入文档的问题。下面是我使用的模式:如何通过Mongoose查询对嵌入文档的数组进行排序?
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的位置。我现在做的排序在JavaScript我检索到的数据之后,从MongoDB中,像这样:
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);
}
});
我读过有关猫鼬所提供的排序API,但我无法弄清楚它是否可用于排序数组嵌入的文件,如果是的话,如果这是一个明智的做法,以及如何将其应用于这个问题。有谁能帮我出来吗?
在此先感谢和欢呼声, 乔治
谢谢杰德。我最终使用了你提出的方法 - 在嵌入时对位置进行排序。对我来说工作得很好。 – BumbleGee 2012-02-23 16:36:56
这也是我的问题,但如何在嵌入时对嵌入文档进行排序? – drinchev 2012-04-01 13:10:08
我已经想通了。您可能是指通过.push或.unshift添加新文档时,它将被正确定位。 – drinchev 2012-04-01 13:34:11