0

I have three fields quantity, price, and total.

I am only updating quantity and price, so total should be calculated automatically.

How can I make sure total is always updated correctly? I guess I should use a collection hook.

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • Is `total` just `quantity` * `price`, or is it based on something else in your collection? How are you doing the updates (allow/deny vs methods)? – David Weldon Nov 19 '15 at 21:01
  • I am updating quantity and price through an autoform with `type="update"`. – Jamgreen Nov 19 '15 at 21:39
  • Simplest solution is not to store `total`. Always calculate it when you need it. – JeremyK Nov 19 '15 at 22:02
  • Not storing it at all is great *unless* you have to search for it. – Michel Floyd Nov 19 '15 at 22:18
  • It won't be appropriate in all scenarios, but you can use the MongoDB aggregation framework to find a calculated value: Orders.aggregate( [ {$project: {date: 1, item: 1, total: {$multiply: ["$price", "$quantity"]} } }, {$match: {total: searchTerm}} ] ); – JeremyK Nov 20 '15 at 00:24

1 Answers1

2

if you're using autoform and simple schema, just use an autovalue

'price': { type: Number },
'quantity': { type: Number },
'total': {
  type: Number,
  autoValue: function () {
    const price = this.field('price');
    const quantity = this.field('quantity');
    if (price.isSet && quantity.isSet) {
      if (this.isInsert) {
        return quantity.value * price.value;
      } else {
        return { $set: quantity.value * price.value };
      }
    }
  }  
}
corvid
  • 10,733
  • 11
  • 61
  • 130