使用猫鼬模型设置打字稿

Kee*_*ert 2 javascript mongoose typescript

无论出于何种原因打字稿不接受我的代码。在该UserScema.pre方法中,打字稿错误表示属性createdAt,并且password在类型 Document( this)上不存在。如何使打字稿接口应用于此方法并返回 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;
Run Code Online (Sandbox Code Playgroud)

我的代码来自这个来源http://brianflove.com/2016/10/04/typescript-declaring-mongoose-schema-model/

Est*_*ask 5

pre参数默认Document为 的泛型方法。如果不是这样,它应该是:

UserSchema.pre<IUserDocument>('save', function(next){ ... });
Run Code Online (Sandbox Code Playgroud)