2012-02-19 45 views
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,但我無法弄清楚它是否可用於排序數組嵌入的文件,如果是的話,如果這是一個明智的做法,以及如何將其應用於這個問題。有誰能幫我出來嗎?

在此先感謝和歡呼聲, 喬治

回答

4

你這樣做是正確的方式,喬治。你的其他選擇是在首先嵌入時按時間排序,或者使用更傳統的非嵌入式路由(或者最小嵌入路由,這樣你可以嵌入一個ID數組或其他東西,但實際上是查詢地點分開)。

+0

謝謝傑德。我最終使用了你提出的方法 - 在嵌入時對位置進行排序。對我來說工作得很好。 – BumbleGee 2012-02-23 16:36:56

+0

這也是我的問題,但如何在嵌入時對嵌入文檔進行排序? – drinchev 2012-04-01 13:10:08

+0

我已經想通了。您可能是指通過.push或.unshift添加新文檔時,它將被正確定位。 – drinchev 2012-04-01 13:34:11

相關問題