Javascript 使用mongoose模型设置typescript
无论出于什么原因,typescript都不接受我的代码。在Javascript 使用mongoose模型设置typescript,javascript,typescript,mongoose,Javascript,Typescript,Mongoose,无论出于什么原因,typescript都不接受我的代码。在UserScema.pre方法中,typescript错误表示属性createdAt,以及password在类型文档中不存在(this)。如何使typescript接口应用于此方法并返回IUserDocument对象 import {Schema, Model, Document, model} from 'mongoose'; import bcrypt from 'bcrypt-nodejs'; export interface I
UserScema.pre
方法中,typescript错误表示属性createdAt
,以及password
在类型文档中不存在(this
)。如何使typescript接口应用于此方法并返回IUserDocument对象
import {Schema, Model, Document, model} from 'mongoose';
import bcrypt from 'bcrypt-nodejs';
export interface IUserDocument extends Document{
createdAt: Date,
username: string,
displayName: string,
email: string,
googleId: string,
password: string,
verifyPassword(password:string): boolean
}
let UserSchema: Schema = new Schema({
createdAt:{
type:Date,
default:Date.now
},
username: {
type:String,
lowercase:true
},
displayName: String,
email: {
type:String,
lowercase:true
},
googleId: String,
password: String
});
UserSchema.pre('save', function(next){
var user = this;
if(!this.createdAt) this.createdAt = Date.now;
if(user.isModified('password')) {
bcrypt.genSalt(10, function(err:any, salt:number){
bcrypt.hash(user.password, salt, null, function(err:any, hash:string){
if(err) return next(err);
user.password = hash;
next();
});
});
} else{
return next();
}
});
UserSchema.methods.verifyPassword = function(password:string){
return bcrypt.compareSync(password, this.password);
}
const User = model<IUserDocument>('User', UserSchema);
export default User;
从“mongoose”导入{Schema,Model,Document,Model};
从“bcrypt nodejs”导入bcrypt;
导出接口IUserDocument扩展文档{
createdAt:Date,
用户名:string,
displayName:string,
电子邮件:string,
googleId:string,
密码:string,
verifyPassword(密码:字符串):布尔值
}
让UserSchema:Schema=newschema({
创建数据:{
类型:日期,
默认值:Date.now
},
用户名:{
类型:字符串,
小写:true
},
displayName:String,
电邮:{
类型:字符串,
小写:true
},
googleId:String,
密码:String
});
UserSchema.pre('save',函数(下一步){
var user=this;
如果(!this.createdAt)this.createdAt=Date.now;
if(user.isModified('password')){
bcrypt.genSalt(10,函数(err:any,salt:number){
bcrypt.hash(user.password、salt、null、函数(err:any、hash:string){
if(err)返回next(err);
user.password=hash;
next();
});
});
}否则{
返回next();
}
});
UserSchema.methods.verifyPassword=函数(密码:字符串){
返回bcrypt.compareSync(password,this.password);
}
const User=model('User',UserSchema);
导出默认用户;
我的代码来自此源。pre
是。如果情况并非如此,则应为:
UserSchema.pre<IUserDocument>('save', function(next){ ... });
UserSchema.pre('save',函数(next){…});
谢谢,这正是解决方法。