简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM