2016-01-06 66 views
2

我有一個Invoice模型,它使用虛擬屬性來計算稅,小計,總計等的值。我遇到的問題是某些虛擬屬性需要能夠以引用其他虛擬屬性。如何使用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的虛擬獲取器。

是否有某種方法告訴M​​ongoose我需要使用getter而不是嘗試讀取不存在的屬性?

回答