You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose Schema默认函数计算SSC报错,是否仅允许使用字段?

问题:Mongoose默认函数计算SSC时出现"expression expected"错误

我尝试计算SSC,规则是将basicSalary乘以0.07%。totalEarnings、totalDeductions和netSalary字段的字段间计算都能正常运行,但SSC字段执行乘法操作时出现“expression expected”错误。想知道是不是默认函数里只能用字段进行计算?

相关代码:

const mongoose = require("mongoose");

const salariesSchema = mongoose.Schema({

  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: function(){
    return this.basicSalary * 0.07%
  } },

  incomeTax: { type: Number, default: 0 },
  medicalInsurance: { type: Number, default: 0 },
  loan: { type: Number, default: 0, default: null },

  totalEarnings: {
    type: Number,
    default: function () {
      return (
        this.basicSalary + this.accomodation + this.transportation + this.bonus
      );
    },
  },

  totalDeductions: {
    type: Number,
    defualt: function () {
      return this.SSC - this.incomeTax - this.medicalInsurance - this.loan;
    },
  },

  netSalary: {
    type: Number,
    default: function () {
      return this.totalEarnings - this.totalDeductions;
    },
  },
});

module.exports = mongoose.model("salarie", salariesSchema);

解答

  • 错误不是因为默认函数只能用字段计算,而是0.07%是无效的JavaScript语法。%是取模运算符,不能直接用来表示百分比。0.07%的正确数值写法是0.0007(或者0.07 / 100)。
  • 修正SSC字段的默认函数:
SSC: { type: Number, default: function(){
  return this.basicSalary * 0.0007;
} },
  • 另外注意totalDeductions字段里的拼写错误:defualt要改成default,否则该字段的默认计算逻辑不会生效。
  • Mongoose的默认函数支持任意合法的JavaScript表达式,只要最终返回对应类型的值即可,并非只能做字段间的加减操作。

内容的提问来源于stack exchange,提问作者Aasem Shoshari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:05:18