简体   繁体   English

用猫鼬模型设置打字稿

[英]Setting up typescript with mongoose model

For whatever reason typescript is not accepting my code. 无论出于何种原因,打字稿都不接受我的代码。 In the UserScema.pre method the typescript error says the properties createdAt , and password do not exist on the type Document ( this ). UserScema.pre方法的打字稿错误说属性createdAtpassword不要在类型文件(存在this )。 How can I make the typescript interface apply to this method and return an IUserDocument object? 如何使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;

My code is derived from this source http://brianflove.com/2016/10/04/typescript-declaring-mongoose-schema-model/ . 我的代码是从此来源http://brianflove.com/2016/10/04/typescript-declaring-mongoose-schema-model/派生的。

pre is generic method which parameter defaults to Document . pre通用方法,其参数默认为Document In case this is not so, it should be: 如果不是这样,应该是:

UserSchema.pre<IUserDocument>('save', function(next){ ... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM