首页 > 解决方案 > 创建自定义 getter

问题描述

如何使文档中的字段具有自定义 getter?我希望该领域随时subtotal返回。productTotal + taxsubtotal

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

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

我不能使用虚拟化,因为我还想findsubtotal.

标签: node.jsmongodbmongoose

解决方案


嗨,我从未使用过猫鼬,但我们实际上可以为 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());

我检查了 mongoose 的文档,找不到与 getter 相关的任何内容


推荐阅读