【发布时间】:2021-04-08 04:56:45
【问题描述】:
我在第 40 行收到以下错误:
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
~~~~~~~~~~~~~
“函数”类型的参数不可分配给“字符串”类型的参数。ts(2345)
根据 IUser,它应该是字符串,我不知道为什么 ts 意味着它是一个函数。
完整的文件:
import { Schema, Document } from 'mongoose';
import bcrypt from 'bcrypt';
const salt: number = 12;
const UserSchema: Schema<IUser> = new Schema({
email: {
type: String,
required: true,
unique: true,
},
name: {
type: String,
required: true,
minlength: 3,
maxlength: 32,
},
password: {
type: String,
required: true,
},
});
// * Hash the password befor it is beeing saved to the database
UserSchema.pre('save', function (next: (err: Error | null) => void) {
// * Make sure you don't hash the hash
if (!this.isModified('password')) {
return next(null);
}
bcrypt.hash(this.password, salt, (err: Error, hash: String) => {
if (err) return next(err);
this.password = hash;
});
});
UserSchema.methods.comparePasswords = function (
candidatePassword: String,
next: (err: Error | null, same: Boolean | null) => void,
) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err) {
return next(err, null);
}
next(null, isMatch);
});
};
export interface IUser extends Document {
email: String;
name: String;
password: String;
}
【问题讨论】:
-
这个问题可能对你有帮助:stackoverflow.com/questions/65704763/…>.
标签: node.js mongodb typescript mongoose bcrypt