node.js - 创建自定义 getter
问题描述
如何使文档中的字段具有自定义 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
.
解决方案
嗨,我从未使用过猫鼬,但我们实际上可以为 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 相关的任何内容
推荐阅读
- matlab - 如何在 Matlab 中按间隔对 3d 矩阵行求和?
- javascript - 在 typeahead selected 事件函数被调用多次时,它应该只调用一次
- mysql - Unknown authentication method error while using wordpress and mysql docker images
- azure - 未找到 Azure Dev Ops url 的 Microsoft appcenter 服务 url
- javascript - 问题重新加载包含 javascript 和 java 代码的 DIV
- asp.net-mvc-5 - 部分视图更新后显示错误数据(asp.net MVC5)
- c++ - 如何设置函数参数以取回填充了从文件中读取的值的二维向量?
- python - SymInitialize python
- android - 多模块清洁架构项目:使 Koin 设置反映正确的 gradle 依赖关系
- google-chrome - Chromebook 自助服务终端模式,禁用切换到 ChromeOS