如何根据两个字段的差异对集合进行排序?

时间:2015-06-27 22:04:12

标签: javascript mongodb meteor

在我的集合中,每个文档都有两个如下所示的值:

{
  originalPrice: 500,
  ourPrice: 420
}

正如您可以想象的那样,我希望用户能够根据他们从我们这里节省购物的数量来排序,而不是从竞争对手那里获得,这对于这个特殊商品来说是80元。

但是,这个值本身不在数据库中,所以我不能简单地做

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

或类似的东西。

在数据库中插入这个数字可能是一件容易的事,但除非让事情以其他方式运作的方法非常复杂,否则我不愿意这样做。

所以我想要一个能做到这一点的功能,

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

并以某种方式使用此值进行排序!

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以在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}})

答案 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>
相关问题