Updating total from quantity and price in Meteor collection

123 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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 };
      }
    }
  }  
}