我有这样的架构,像basicSalary
这样的字段可以由管理员通过 Jmeter 板UI进行编辑,pre保存钩子可以很好地计算字段,然后pre updateOne钩子可以在管理员编辑文档时更新文档
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();
});
salariesSchema.pre("updateOne", 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();
});
路线〉薪金..js
const Salary = require("../models/Salary");
const editSalary = async (req, res) => {
try {
const salary = Salary.findById(req.body._id);
await salary.updateOne({ $set: req.body });
res.status(200).json("salary has been updated successfully");
} catch (err) {
console.log(err);
res.status(400).json(err);
}
};
例如,如果admin将basicSalary
增加了50,则totalEarnings
和netSalary
的值也应该根据pre updateOne
挂钩中的计算更新50,但这不起作用,这里出了什么问题?
2条答案
按热度按时间2vuwiymt1#
您应该为其他类型的查询创建单独的
pre
挂钩。例如,您可以添加updateOnepre
挂钩:rta7y2nd2#
我发现我不能直接使用
this.fieldName
访问字段,我通过使用转换为数字的this.get("fieldName")
,并使用this.set
(参见文档)而不是return fieldName = expression
来解决它“如果你有更好的方法,请告诉我"