It looks like @Mohammad has helped you with the bcrypt
implementation. I can help you with the typescript errors!
UserDoc
is a typescript interface, so it shouldn't have fields like required
. It should just describe the type of a UserDoc
object. Properties are required by default. We use ?:
if they are optional, but it looks like all are required here.
export interface UserDoc extends Document {
name: string;
email: string;
password: string;
dateJoined: string;
matchPassword: (pw: string) => Promise<boolean>
}
When you create userSchema
, you tell typescript that this is the schema for a UserDoc
- not just any Document
- by setting the generic variable of the Schema
constructor to UserDoc
.
const userSchema = new Schema<UserDoc>({ ...
This clears up the errors in userSchema.methods.matchPassword
since we know that this.password
is a string
. We also know that enteredPassword
is a string
because we defined the args for this matchPassword
method in the UserDoc
interface.
For some reason, the pre
method doesn't know our document type automatically. But the pre
method is itself a generic function, so we can specific again that our doc is a UserDoc
.
userSchema.pre<UserDoc>( ...
This is dumb but we have to specify the generic again when we create the model.
const User = mongoose.model<UserDoc>("User", userSchema);
Now User
has type mongoose.Model<UserDoc, {}>
and any methods that you call should return a UserDoc
instead of just a Document
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…