【发布时间】:2022-09-22 21:54:12
【问题描述】:
我有这个模式和像basicSalary这样的字段可以由管理员通过仪表板UI编辑,预保存钩子第一次可以正常工作,但是如果一个字段被编辑,它不会动态计算totalEarnings,@987654323 @ 和netSalary,所以每次更改文档时我都需要预先保存钩子以触发,该怎么做?
const salariesSchema = mongoose.Schema({
employeeId: {
type: mongoose.Schema.Types.ObjectId,
ref: \"employee\",
required: true,
},
month: { type: String, required: true },
year: { type: String, required: true },
basicSalary: { type: Number, default: 0, required: true },
accomodation: { type: Number, default: 0 },
transportation: { type: Number, default: 0 },
bonus: { type: Number, default: 0 },
SSC: { type: Number, default: 0 },
incomeTax: { type: Number, default: 0 },
medicalInsurance: { type: Number, default: 0 },
loan: { type: Number, default: 0, default: null },
totalEarnings: { type: Number },
totalDeductions: { type: Number },
netSalary: { type: Number },
});
salariesSchema.pre(\"save\", function (next) {
this.SSC = this.basicSalary * 0.07;
this.totalEarnings =
this.basicSalary + this.accomodation + this.transportation + this.bonus;
this.totalDeductions =
this.incomeTax + this.medicalInsurance + this.loan + this.SSC;
this.netSalary = this.totalEarnings - this.totalDeductions;
next();
});
标签: mongodb mongoose mongoose-schema