在我的集合中,每个文档都有两个值,如下所示:
{
originalPrice: 500,
ourPrice: 420
}正如您可以想象的那样,我希望用户能够根据他们从我们而不是竞争对手那里节省的购物费用进行排序,在这种情况下,竞争对手的价格是80。
但是,这个值本身不在数据库中,所以我不能简单地这样做
Goods.find({}, {sort: saveAmount: 1})或者其他类似的东西。
在数据库中插入这个数字可能是一项简单的任务,但除非让事情以另一种方式工作的方法非常复杂,否则我不希望这样做。
所以我想要一个函数来做这件事,
var saveAmount = function(originalPrice, ourPrice) {
return originalPrice - ourPrice
}并以某种方式使用该值进行排序!
我该怎么做呢?
发布于 2015-06-28 06:33:00
您可以在MongoDB查询中执行此操作,但不能使用meteor。因此,您必须按照您的建议使用单独的字段。下面是你可以做的:
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}})发布于 2015-06-28 07:37:59
下面是一个如何在客户机上按排序显示商品的示例:
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>https://stackoverflow.com/questions/31093980
复制相似问题