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

TypeScript Mongoose中间件与静态函数在Kubernetes-Docker环境无法调用

问题根因

这是Mongoose使用的典型顺序错误,和你用的Kubernetes-Docker环境没有关系:所有schema的中间件、静态方法、实例方法必须在调用model()注册模型之前定义,你当前代码顺序完全颠倒,先注册模型再修改schema,已经生成的Model实例不会同步这些变更,所以两类逻辑都无法触发。

// 你当前的错误执行顺序
const User = model<UserDocument, UserModel>("User", userSchema); // 第一步先注册模型
userSchema.statics.build = function () {} // 第二步才加静态方法
userSchema.pre("save", async function () {}) // 第三步才加中间件

修复方案

只需要调整User模型文件里的代码顺序,把model()调用放到所有schema扩展逻辑的最后即可,修改后的核心代码如下:

// 前面的interface定义、schema实例化代码保持不变
const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

// 先定义静态方法
userSchema.statics.build = function (attrs: UserAttrs) {
  return new this(attrs); // 这里替换成this更规范,避免还未定义User就调用的问题
};

// 再定义save前置中间件
userSchema.pre(
  "save",
  async function (this: UserDocument, next): Promise<void> {
    console.log("Saving . . . ");
    if (this.isModified("password")) {
      const hashedPassword = await Password.toHash(this.get("password"));
      this.set("password", hashedPassword);
    }
    next();
  }
);

// 最后注册模型
const User = model<UserDocument, UserModel>("User", userSchema);

export { User };

修改后重新运行代码,build静态方法和save中间件就会正常触发。

内容的提问来源于stack exchange,提问作者Erfan Motallebi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:54:03