我正在尝试访问猫鼬模式的模式方法,但出现错误。 (使用打字稿工作)
架构
const userSchema: Schema<IUser> = new Schema(
{
name: {
type: String,
required: [true, "Name is required"],
maxLength: [50, "Name should be smaller than 50 characters"],
lowercase: true,
trim: true,
},
password: {
type: String,
required: [true, "Password is required"],
select: false,
minLength: [8, "Password must be at least 8 characters"],
},
// ...other props
);
架构方法
userSchema.methods = {
comparePassword: async function (plainTextPassword: string) {
return await bcrypt.compare(plainTextPassword, this.password);
},
};
用法
const user = await User.findOne({ email }).select("+password");
let isPassCorrect;
if (user) isPassCorrect = await user.comparePassword(password);
这里我收到一个错误
Property 'comparePassword' does not exist on type 'Document<unknown, {}, IUser> & IUser & Required<{ _id: ObjectId; }>'.
我尝试使用静态而不是模式,但它也给出了错误。
任何帮助将不胜感激...... 预先感谢。
您遇到的错误是由于 TypeScript 无法将您的
comparePassword
方法识别为 IUser
接口的一部分,该接口用于输入猫鼬模型。在 Mongoose 中,添加到模式的方法不会被 TypeScript 自动识别。您需要在接口中显式声明它们,以使 TypeScript 意识到这些自定义模式方法。
要解决此问题,您应该使用包含自定义方法的接口来扩展
Document
类型。具体方法如下:
mongoose.Document
扩展并包含您的自定义方法签名。假设 IUser
是用户模式的原始接口,您将为模式方法创建另一个接口:import { Document } from 'mongoose';
interface IUserMethods extends Document {
comparePassword: (plainTextPassword: string) => Promise<boolean>;
}
IUserMethods
) 作为文档类型。这样,TypeScript 将了解您的自定义方法。以下是修改 Schema
和模型创建的方法:import mongoose, { Schema } from 'mongoose';
import bcrypt from 'bcrypt';
// Assuming IUser is your original interface for user attributes
interface IUser {
name: string;
password: string;
// Add other properties here
}
// New interface for methods
interface IUserMethods extends Document {
comparePassword: (plainTextPassword: string) => Promise<boolean>;
}
const userSchema: Schema<IUser> = new Schema({
// Schema definition remains the same
});
// Define methods
userSchema.methods.comparePassword = async function (this: IUserMethods, plainTextPassword: string): Promise<boolean> {
return bcrypt.compare(plainTextPassword, this.password);
};
// Create the model
const User = mongoose.model<IUserMethods>('User', userSchema);
此方法会向 TypeScript 通知您已添加到架构中的自定义方法(在本例中为
comparePassword
),从而解决您遇到的错误。现在,当您使用 User
模型时,TypeScript 将识别 comparePassword
方法并相应地检查其用法。
请记住,每次向架构添加要在 TypeScript 代码中使用的新方法时,您都需要扩展接口以包含这些方法签名,以使 TypeScript 能够识别这些自定义方法。