Ошибка машинописного текста в методе mon goose pre: неожиданный псевдоним 'this' к локальной переменной - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь реализовать аутентификацию на основе MongoDB и Nest JS для приложения Ioni c и получаю следующее сообщение об ошибке после выполнения запроса POST к маршруту api / users :

[Гнездо] 85372 - 26.03.2020, 14:04:49 [ExceptionsHandler] Невозможно прочитать свойство 'пароль' из неопределенного + 23790мс

Внутри моих пользователей. Файл schema.ts a получает сообщение об ошибке:

Неожиданное наложение 'this' на локальную переменную. eslint (@ typescript-eslint / no-this-alias)

Мой users.schema.ts выглядит следующим образом (прокомментировал строку с ошибкой):

import * as mongoose from 'mongoose';
import * as bcrypt from 'bcryptjs'

export const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        unique: true,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    updatedAt: {
        type: Date,
        default: Date.now
    }
});

UserSchema.pre('save', function (next) {
    const user = this; // This is marked as an error in vs code
    if (!user.isModified('password')) return next();

    bcrypt.genSalt(10, (err, salt) => {
        if (err) return next(err);
        bcrypt.hash(this.user.password, salt, (err, hash) => {
            if (err) return next();
            this.user.password = hash;
            next();
        });
    });
});

UserSchema.methods.checkPassword = (attempt, callback) => {
    bcrypt.compare(attempt, this.user.password, (err, isMatch) => {
        if (err) return callback(err);
        callback(null, isMatch);
    })
}

Я попытался реализовать ту же схему с помощью функции стрелки, но затем я получил следующее сообщение об ошибке после выполнения POST-запрос к api / users :

[Nest] 85947 - 26.03.2020, 14:09:30 [ExceptionsHandler] Невозможно прочитать свойство isModified из undefined + 22567мс

UserSchema.pre('save', (next) => {
    if (!this.user.isModified('password')) return next();

    bcrypt.genSalt(10, (err, salt) => {
        if (err) return next(err);
        bcrypt.hash(this.user.password, salt, (err, hash) => {
            if (err) return next();
            this.user.password = hash;
            next();
        });
    });
});

Что я здесь не так делаю?

...