I'm currently working on setting up authentication using MongoDB and NestJS for an Ionic application. After sending a POST request to the api/users route, I encountered the following error message:
[Nest] 85372 - 03/26/2020, 14:04:49 [ExceptionsHandler] Cannot read property 'password' of undefined +23790ms
In my users.schema.ts file, I came across this error message:
Unexpected aliasing of 'this' to local variable.eslint(@typescript-eslint/no-this-alias)
The snippet from my users.schema.ts file where the error occurs is as follows (the problematic line is commented out):
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);
})
}
When attempting to use an arrow function for the same schema, I faced another error message after sending a POST request to api/users:
[Nest] 85947 - 03/26/2020, 14:09:30 [ExceptionsHandler] Cannot read property 'isModified' of undefined +22567ms
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();
});
});
});
What could be the issue here?