【问题标题】:Mongoose fire pre hook every time a doc is edited每次编辑文档时,Mongoose 都会触发预钩子
【发布时间】: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


    【解决方案1】:

    您应该为其他类型的查询创建单独的 pre 挂钩。例如,您可以添加更新一pre钩子:

    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() {
      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();
    });
    

    【讨论】:

    • 但它说Salary.pre 不是函数。
    • 我更新了我的答案。你能再试一次吗?
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2017-02-13
    • 2016-06-29
    • 1970-01-01
    • 2018-05-07
    • 2018-01-14
    • 2020-01-12
    相关资源
    最近更新 更多