我有一个Invoice模型,它使用虚拟属性计算税,小计,总数等值。我遇到的问题是某些虚拟属性需要能够引用其他虚拟属性。
例如,以下是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);
现在要了解这个问题,请看一下税收的虚拟定义&#39; ...
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的虚拟getter。
有没有办法告诉Mongoose我需要使用getter而不是尝试读取一个不存在的属性?
答案 0 :(得分:4)
你试过def login(request):
password=request.POST['password']
email=request.POST['email']
try:
d2 = Register.objects.latest('created_at')
registered = Register.objects.get(email = email)
except:
return HttpResponse(Register.userManager.not_found_email())
pw_bytes = password.encode('utf-8')
hashed = bcrypt.hashpw(pw_bytes, registered.salt)
print hashed
if hashed:
print hashed
print registered.password
return HttpResponse(Register.userManager.incorrect_password())
return render(request, 'validation_app/success.html')
吗?
这似乎是使用虚拟的明确方式。
从这个问题得到它: https://github.com/Automattic/mongoose/issues/2326 遗憾的是没有找到任何相关内容。