2014-12-05 75 views
0

我有兩個MongoDB集合CustomerUser1:1的關係。我試圖使用Mongoose Population查詢這兩個文檔,並按User.name對它們進行排序。正確的語法排序貓鼬3.x填充文件

以下沒有任何工作。我的貓鼬是3.8.19。

Customer 
    .find({}) 
    .populate("user", "name email phone") 
    .sort({ "name": 1 }) 
    .exec() 

Customer 
    .find({}) 
    .populate("user", "name email phone", null, { sort: { 'name': 1 } }) 
    .exec() 

Customer 
    .find({}) 
    .populate({ 
     path: "user", 
     select: "name email phone", 
     options: { sort: { "name": 1 }} 
    }). 
    exec() 

Customer 
    .find({}) 
    .populate({ 
     path: "user", 
     select: "name email phone", 
     options: { sort: [{ "name": 1 }]} 
    }) 
    .exec() 

我發現How to sort a populated document in find request?,但對我沒有成功。

這將是類似下面的SQL:

SELECT customer.*, user.name, user.email, user.phone FROM customer 
JOIN user ON customer.user_id = user.id 
ORDER BY user.name ASC 
+2

您無法在填充字段上對文檔進行排序。 http://stackoverflow.com/questions/19428471/node-mongoose-3-6-sort-query-with-populated-field – JohnnyHK 2014-12-05 15:10:42

回答

5

感謝@JohnnyHK in comment,這是不可能的MongoDB中和Moongose的填充字段進行排序。 The only option is to sort the entire array of results manually

Mongo沒有連接。收到所有結果後,手動分類填充文檔的唯一方法是手動輸入 。

我解決了這個問題,使用Array.sort([compareFunction])來排序從Mongoose查詢產生的輸出。但是,在對大量數據進行排序時,這可能會對性能產生重大影響。

作爲一個邊節點,我正考慮轉移到一個關係數據庫與node.js.

-1

我不知道爲什麼人們說你不能排序填充的字段....

model.findOne({name: request.params.posts}) 
    .populate('messages', '_id message createDate', null, { sort: { 'createDate': -1 } }) 
    .exec(function(error, results) { 
}) 

在哪裏我的模型「上崗」,在它的ObjectID消息數組,即人口這裏按照它的createDate排序。它效果很好。

+0

它可能可以按每個帖子排序消息,而不是所有的全部結果。你的解決方案非常類似於我的第二個例子,它無法通過填充文檔對整個結果進行排序。 – Sithu 2015-08-01 03:41:21