[英]Sorting across joined collections
我有兩個收藏,
優惠是產品的子項,通過product
密鑰關聯。 產品通過user
密鑰與用戶關聯:
products : function(){
return Products.find({'user': Meteor.userId()}).fetch();
},
offers: function(){
return Offers.find({product: this._id}).fetch();
}
html:
{{#each products}}
{{#each offers}}
{{/each}}
{{/each}}
我想在mongodb中為offers.price應用排序當我申請時,它只在每個產品中排序我如何在所有產品中按Offers.price
排序?
您不能有兩個集合的嵌套循環並按內部集合排序:
{{#each products}}
{{#each offers}}
{{/each}}
{{/each}}
至少一般來說這是不可能的,因為(一般而言)產品“A”可能有最高的報價,也有最低的報價。
您可以做的是創建一個連接的產品和優惠數組,然后按價格鍵對該數組進行排序。 由於要約是產品的子項,您可以執行以下操作:
Template.myTemplate.helpers({
joinedArray() {
let array = [];
Products.find({ 'user': Meteor.userId() }).forEach(p => {
Offers.find({ product: p._id }).forEach(o => {
array.push({ productName: p.name, offerName: o.name, offerPrice: o.price });
});
});
return _.sortBy(array,'offerPrice');
}
});
排序是使用下划線的sortBy函數完成的。
在array.push
行中,我對集合中存在哪些鍵、要在助手中返回哪些鍵以及如何命名這些鍵做了一些假設。 在排序中,我假設您想按價格升序排序。 如果你想要相反的順序,那么你可以.reverse()它。
如果您的Offers
集合被非規范化並包含來自Products
的相關字段,那么您可以直接對該集合進行排序,並在您的助手中在單個循環中使用它的鍵。
用這樣的東西排序:
return Offers.find({}, {sort: {price: 1}});
但我不知道你到底想在這里做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.