首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法访问Typescript中的mongoose架构上下文

无法访问Typescript中的mongoose架构上下文
EN

Stack Overflow用户
提问于 2016-07-25 00:54:22
回答 2查看 1.3K关注 0票数 4

我正在尝试将.pre.method.static函数应用于我的Mongoose模式。

我有以下代码,但是我的this要么在错误的上下文中,要么我误解了模式。

代码语言:javascript
运行
复制
export interface IUser extends mongoose.Document {
    email: string;
    password: string;
    firstName: string;
    lastName: string;
    comparePassword(password: string, callback: Function): void;
}

class UserSchema {
    static get schema(): mongoose.Schema {
        let userSchema = new mongoose.Schema({
            email: {
                type: String,
                unique: true,
                lowercase: true
            },
            firstName: {
                type: String,
                required: true
            },
            lastName: {
                type: String,
                required: true
            },
            password: {
                type: String,
                select: false
            }
        });

        userSchema.pre('save', this.saveHandler);        
        userSchema.method('comparePassword', this.comparePassword);

        return userSchema;
    }

    static saveHandler(next) {
        let user = this.schema;
        if(!user.isModified('password')) {
              return next();
         }
          bcrypt.genSalt(10, (err, salt) => {
              bcrypt.hash(user.password, salt, (err, hash) => {
                  user.password = hash;
                  next();
              });
          });
    }

    static comparePassword(password: string, callback: Function) {
        let user = this.schema;
        bcrypt.compare(password, user.password, (err, isMatch) => {
            callback(err, isMatch);
        });
    }
}

export const UserModel = mongoose.model<IUser>('User', UserSchema.schema);

Typescript抛出错误,Property 'isModified' does not exist on type 'Schema'.

然而,在javascript中:

代码语言:javascript
运行
复制
var schema = new Schema({
    email: { type: String, unique: true, lowercase: true },
    password: { type: String, select: false },
    firstName: String,
    lastName: String,
});

schema.pre('save', function(next) {
    var user = this;
    if(!user.isModified('password')) {
        return next();
    }
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(user.password, salt, function(err, hash) {
            user.password = hash;
            next();
        });
    });
});

具有正确的this上下文。我如何正确地构造我的Typescript代码才能达到同样的效果呢?

EN

Stack Overflow用户

发布于 2021-03-05 17:26:46

使用不带箭头函数的函数工作起来就像Fedoranimus所说的那样

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38554466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档