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

Mongoose静态方法中this为undefined问题求助

Mongoose静态方法中this为undefined的问题排查提示

以下是针对你遇到的Mongoose 6.5.1静态方法findUser中this为undefined、调用this.findOne报错问题的排查方向:

  • 修正类型定义不匹配问题
    你的IUserModel接口定义findUser的参数为string,但静态方法的参数却是Pick<IUser, "email">,类型不一致可能导致TypeScript编译时干扰函数上下文绑定。将静态方法的参数改为string,与接口保持一致:

    userSchema.statics.findUser = async function (
      email: string
    ): Promise<IUser | null> {
      console.log("this", this);
      try {
        const user = await this.findOne({ email }).exec();
        return user;
      } catch (err: any) {
        return err;
      }
    };
    
  • 检查TypeScript严格模式配置
    若tsconfig.json中开启了strict或noImplicitThis模式,可能会影响函数的this绑定上下文。可以临时关闭noImplicitThis进行测试,确认是否是配置导致的问题。

  • 确保静态方法调用方式正确
    调用静态方法时必须通过模型构造函数直接调用(如User.findUser(email)),禁止使用解构赋值的方式调用(如const { findUser } = User; findUser(email)),后者会丢失this的上下文绑定。

  • 确认静态方法挂载时机
    你当前在Schema创建后、Model生成前挂载静态方法的时机是正确的,但要排查是否有其他代码修改了userSchema.statics对象,导致方法的上下文被意外篡改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:24:20