2015-06-27 82 views
0

在我的收藏,每個文檔有看起來像這樣的兩個值:如何根據兩個字段的差異對集合進行排序?

{ 
    originalPrice: 500, 
    ourPrice: 420 
} 

正如你可以想像,我希望用戶能夠通過多少,他們會從我們這裏,而不是節省購物排序從競爭對手中,在這個特別的好是80

但是,該值本身不是在數據庫中,所以我不能簡單地做

Goods.find({}, {sort: saveAmount: 1}) 

或類似的東西。

將這個數字插入數據庫可能是一件容易的事情,但除非以其他方式讓事情工作的方法非常複雜,否則我寧願不這樣做。

所以我想一個函數,這樣做,

var saveAmount = function(originalPrice, ourPrice) { 
    return originalPrice - ourPrice 
} 

並以某種方式使用這個值來排序!

我該怎麼做?

+2

你有看着使用[聚合](http://docs.mongodb.org/manual/aggregation/)? –

+0

@JasonCust不,第一次聽說它! – Yeats

+0

您是否試過[Map-reduction](http://docs.mongodb.org/manual/core/map-reduce/)? – Alp

回答

1

你可以在MongoDB查詢中完成,但不能用流星。因此,您必須按照您的建議使用單獨的字段。這裏是你可以做什麼:

function setDifference (doc) { 
    var difference = doc.originalPrice - doc.ourPrice 
    Goods.update(doc._id, { $set: { difference: difference } }) 
} 

Goods.find().observe({ 
    added: setDifference, 
    updated: setDifference 
}) 

如果使用的是簡單的模式,你可以使用autoValue

... 
difference: { 
    type: Number, 
    autoValue: function() { 
    return this.field('originalPrice').value - this.field('ourPrice').value 
    } 
} 
... 

反正現在你可以排序difference

Goods.find({}, {sort: {difference: -1}}) 
1

這裏是你如何能顯示在有序的商品在客戶端上的例子:

JS

Template.myTemplate.helpers({ 
    sortedGoods: function() { 
    return _.sortBy(Goods.find().fetch(), function(good) { 
     return good.originalPrice - good.ourPrice; 
    }); 
    } 
}); 

HTML

<template name="myTemplate"> 
    {{#each sortedGoods}} 
    <div class="good">{{name}}: ${{ourPrice}}</div> 
    {{/each}} 
</template> 
+0

不知道我會如何使用這個幫手!另外,如果出現問題,我在出版物中使用了「限制」。 – Yeats

+0

是的,這是一個不錯的解決方案,但出於顯而易見的原因,它與出版物上的「限制」一起發揮不佳。同樣的事情將不得不在服務器上完成。 – Yeats

+0

這很有道理。這是我在上面的問題中想要了解的。如果您需要了解發布時的差異,則應將其存儲爲單獨的字段。這是唯一有效的解決方案。 –

相關問題