Jamgreen
Jamgreen

Reputation: 11059

Updating total from quantity and price in Meteor collection

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.

Upvotes: 0

Views: 117

Answers (1)

corvid
corvid

Reputation: 11197

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

Upvotes: 2

Related Questions