我收到此错误“文档类型上不存在属性“密码””。那么谁能告诉我的代码是否有问题?
const userSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
name: { type: String, required: true }
});
userSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (err: mongoose.Error, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
您需要根据 mongoose 文档使用预保存挂钩在此处添加类型,预挂钩定义为,
/**
* Defines a pre hook for the document.
*/
pre<T extends Document = Document>(
method: "init" | "validate" | "save" | "remove",
fn: HookSyncCallback<T>,
errorCb?: HookErrorCallback
): this;
如果您有如下所示的界面,
export interface IUser {
email: string;
password: string;
name: string;
}
使用预保存挂钩添加类型,
userSchema.pre<IUser>("save", function save(next) { ... }
我不知道这是否有帮助,因为这个问题现在已经过时了,但是我尝试过这个
import mongoose, { Document } from 'mongoose';
const User = mongoose.model<IUser & Document>("users", UserSchema);
type IUser = {
username: string
password: string
}
mongoose.model
需要一个文档类型,并且您想要扩展该文档,因此统一这两种类型
您还可以将接口类型传递给模式本身。
import { model, Schema, Document } from 'mongoose';
const userSchema = new mongoose.Schema<IUser>({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
name: { type: String, required: true }
});
interface IUser extends Document{
email: string;
password: string;
name: string;
}