创建自定义吸气剂

时间:2020-06-18 00:14:10

标签: node.js mongodb mongoose

如何使文档中的字段具有自定义getter?我希望subtotal字段在我收到productTotal + tax时返回subtotal

const item = new mongoose.Schema({
    payment: {
        productTotal: Number,
        tax: Number,
        subtotal: Number, // (productTotal + tax)
    }
});

const Item = mongoose.model('Item', item);

我无法使用虚拟化,因为我还希望能够在find上使用subtotal

1 个答案:

答案 0 :(得分:0)

嗨,我从未使用过猫鼬,但我们可以为我猜想该代码可行的Item模型创建一个原型?

const item = new mongoose.Schema({
  payment: {
    productTotal: Number,
    tax: Number,
  },
});
const Item = mongoose.model("Item", item);
Item.prototype.subtotal = function () {
  return this.payment.productTotal + this.payment.tax;
};

const newItem = new Item({ payment: { productTotal: 10, tax: 10 } });
// Obv you need to call it as function :)
console.log(newItem.subtotal());

我检查过猫鼬的文档找不到与getter相关的任何内容

相关问题