1

代码是,

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

console.log(userSchema);

userSchema.statics.build = (user: UserAttrs) => {
  return new User(user);
};

userSchema.pre("save", async function (next) {
  if (this.isModified("password")) {
    const hashed = await Password.toHash(this.get("password"));
    this.set("password", hashed);
  }
  next();
});

现在,我遇到的错误是,

[auth] > auth@1.0.0 start /app
[auth] > ts-node-dev src/index.ts
[auth]
[auth] [INFO] 12:46:59 ts-node-dev ver. 1.0.0 (using ts-node ver. 9.0.0, typescript ver. 3.9.7)
[auth] Compilation error in /app/src/models/user.ts
[auth] [ERROR] 12:47:04 ⨯ Unable to compile TypeScript:
[auth] src/models/user.ts(37,12): error TS2551: Property 'statics' does not exist on type 'Schema'. Did you mean 'static'?
[auth] src/models/user.ts(46,3): error TS2554: Expected 1 arguments, but got 0.

静态属性确实存在于模式对象中,并且在我 console.log(userSchema) 时会显示。我认为这与 kubernetes 和 skaffold 有关。知道如何解决这个问题吗?

4

1 回答 1

1

我认为这可能会有所帮助

首先,您必须创建 3 个接口。

interface UserAttrs {
  email: string;
  password: string;
}

interface UserModel extends mongoose.Model<UserDoc> {
  build(attrs: UserAttrs): UserDoc;
}

interface UserDoc extends mongoose.Document {
  email: string;
  password: string; 
}

然后在你的模式的中间件中,你必须声明你正在使用的变量的类型

userSchema.pre("save", async function (this: UserDoc, next: any) {
  if (this.isModified("password")) {
    const hashed = await Password.toHash(this.get("password"));
    this.set("password", hashed);
  }
  next();
});

const User = mongoose.model<UserDoc, UserModel>('User', userSchema);

我发现的相关问题

于 2020-12-04T21:25:20.327 回答