簡體   English   中英

Mongoose 方法和 Typescript - 此屬性未定義

[英]Mongoose Methods and Typescript - this property is undefined

我正在使用 node、express 和 mongoose 開發一個打字稿應用程序一個寧靜的 api。

我有一個身份驗證控制器,帶有附加到POST: /api/auth的存儲功能。 用戶傳入他們的電子郵件和密碼以將其與散列版本進行比較。

但是use.model.ts的 comparePassword 函數不起作用,因為this.password未定義。

auth.controller.ts

import { Request, Response, NextFunction } from 'express';

import User from './../users/user.model';
import jwt from 'jsonwebtoken';
import Config from './../../config/config';

class AuthController {

    private config: any;

    constructor() {

        this.config = new Config();

    }

    public async store(req: Request, res: Response): Promise<any> {

        const input = req.body;

        console.log(input);
        try {

            let user = await User.findOne({ 'email': input.email });

            if (!user) {
                throw {};
            }
            console.log(user);

            user.schema.methods.comparePassword(input.password, (err: any, isMatch: any) => {

                if (err || !isMatch) {

                    return res.status(401).json({
                        success: false,
                        status: 401,
                        data: { err, isMatch },
                        message: 'Authentication Failed, wrong password',
                    });

                }

                if (!err && isMatch) {

                    const token = jwt.sign({ sub: user._id }, this.config.jwt.secretOrKey);

                    return res.status(200).json({
                        success: true,
                        status: 200,
                        data: { user, token },
                        message: 'Authentication Successful',
                    })

                }


            })

        } catch (err) {

            return res.status(404).json({
                success: false,
                status: 404,
                data: err,
                message: 'Failed to Authenticate'
            })

        }


    }
}

export default AuthController;

用戶模型.ts

import { Schema, Model, Document, model } from 'mongoose';
import bcrypt from 'bcryptjs';
import { UserInterface } from './user.interface';


const UserSchema = new Schema({

    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },

}, {
        timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
    });


UserSchema.pre('save', function (next) {
    let user = <UserInterface>this;
    let SALT_WORK_FACTOR = 10;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(user.password, salt, function (err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});

UserSchema.methods.comparePassword = function (candidatePassword: any, cb: any) {

    //let user = <UserInterface>this;

    console.log(candidatePassword);
    console.log(this.password);

    bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};



const User = model<UserInterface>('Users', UserSchema);

export default User;

我在另一個不使用打字稿的項目中使用了類似的 comparePassword 函數。 所以我不確定為什么“this”是未定義的並且沒有設置為貓鼬用戶對象。

這是我為繞過打字稿問題所做的工作。

const self:any = this;

用法示例:

UserSchema.methods.comparePassword = function (candidatePassword: any, cb: any) {
    const self:any = this;

    console.log(candidatePassword);
    console.log(self.password);

    bcrypt.compare(candidatePassword, self.password, function (err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

此外,如果您很着急並且不想創建界面,您可以在您的活動進行此操作。

UserSchema.pre<any>('save', function(next) {
   if (!this.isModified('password')) 
       return next();
   ...
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM