属性 'signup' 的类型在映射类型中循环引用自身的错误——当mongoose的静态方法使用 'this' 时出现

前端开发 2026-07-09

如果我的模式中有多个静态方法,其中一个或多个使用 'this' 关键字,该如何实现?

我目前有这个模式,看起来可以正常工作

https://i.sstatic.net/JpTIt4I2.png

但向模式中添加任何额外的静态方法都会导致这个错误

https://i.sstatic.net/xa68KtiI.png

问题似乎出在使用 'this' 关键字的静态方法上,因为当存在多个不使用 'this' 的函数时,就不会报错。

statics: {
    test: async function () {return "test"},
    test2: async function () {return "test2"}
}

有没有解决这个问题的办法?谢谢。

[编辑] 按照Hussain的示例,我终于让它工作了。之前我没有为我的静态函数中的 'this' 定义类型,而让mongoose为模型推断类型 —— [不是mongoose.Schema({...}),而是mongoose.Schema<模型类型在此>({...})]。现在看起来一切都完整了 工作代码片段

解决方案

问题在于 typescript 在把它们全部组合在一起时试图对this进行推断,从而导致循环引用问题。

因此,解决方法是:在你的代码中把统计信息定义在schema内部,请将它们从schema分离开来,如下所示

const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
  }
);

const model = Model<YourModelType> & {
  signup(email: string, password: string);
};
userSchema.statics.signup = async function (
  this: model, // This requires for type checking and this refers to your mdel type
  email: string,
  password: string
) {
  const exists = await this.findOne({ email });
  if (exists) {
    throw new Error("Email already in use");
  }

  const salt = await bcrypt.genSalt(10);
  const hash = await bcrypt.hash(password, salt);

  return this.create({ email, password: hash });
};
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章