如何使用Mongoose从另一个虚拟内部访问虚拟属性

我有一个发票模型,使用虚拟属性来计算税,小计,总计等值。我有的问题是,一些虚拟属性需要能够引用其他虚拟属性。

例如,这里是发票的Mongoose模式:

var InvoiceSchema = Schema({ number: String, customer: {ref:String, email:String}, invoiceDate: {type: Date, default: Date.now}, dueDate: {type: Date, default: Date.now}, memo: String, message: String, taxRate: {type:Number, default:0}, discount: { value: {type:Number, default:0}, percent: {type:Number, default:0} }, items: [ItemSchema], payment: {type: Schema.Types.ObjectId, ref: 'Payment'} }); InvoiceSchema.virtual('tax').get(function(){ var tax = 0; for (var ndx=0; ndx<this.items.length; ndx++) { var item = this.items[ndx]; tax += (item.taxed)? item.amount * this.taxRate : 0; } return tax; }); InvoiceSchema.virtual('subtotal').get(function(){ var amount = 0; for (var ndx=0; ndx<this.items.length; ndx++) { amount += this.items[ndx].amount; } return amount; }); InvoiceSchema.virtual('total').get(function(){ return this.amount + this.tax; }); InvoiceSchema.set('toJSON', { getters: true, virtuals: true }); var ItemSchema = Schema({ product: String, description: String, quantity: {type: Number, default: 1}, rate: Number, taxed: {type: Boolean, default: false}, category: String }); ItemSchema.virtual('amount').get(function(){ return this.rate * this.quantity; }); ItemSchema.set('toJSON', { getters: true, virtuals: true }); module.exports = mongoose.model('Invoice', InvoiceSchema); 

现在了解这个问题,看看“税收”的虚拟定义…

 InvoiceSchema.virtual('tax').get(function(){ var tax = 0; for (var ndx=0; ndx<this.items.length; ndx++) { var item = this.items[ndx]; tax += (item.taxed)? item.amount * this.taxRate : 0; } return tax; }); 

…在这个例子中,当在一个虚拟内调用item.amount时,并不使用item.amount的虚拟获取器。

有什么办法告诉mongoose,我需要使用getter而不是试图读取一个不存在的属性?

你有没有尝试item.get('amount') ? 这似乎是使用虚拟的明确方式。

从这个问题得到它: https : //github.com/Automattic/mongoose/issues/2326没有find其他相关的不幸的。