0

The problem start when I use the bcrypt middleware to encrypt my password. Whitout bcrypt I could save the users, but with it not now.

My users.js file

'use strict'

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const bcrypt = require('bcrypt')

const UserSchema = new Schema({
    email: { type: String, unique: true, lowercase: true },
    displayName: String,
    password: { type: String, select: false }
})

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

    bcrypt.genSalt(10, (err, salt) => {
        if (err) return next(err)

        bcrypt.hash(user.password, salt, null, (err, hash) => {
            if (err) return next(err)

            user.password = hash
            next();
        })
    })
})

module.exports = mongoose.model('User', UserSchema)

My router.js file:

const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const User = require('./model/user')
const bcrypt = require('bcrypt')


router.post('/user', (req, res) => {
    console.log(req.body)
    let user = new User()
    user.email = req.body.email
    user.displayName = req.body.displayName
    user.password = req.body.password

    user.save((err, stored) => {
        res.status(200).send({
            user: stored
        })
    })
})

This is the server response:

{}

My db is not affected...

Leo
  • 1

1 Answers1

1

I can see two mistakes in the provided code:

1. this in the pre-save middleware is not a user document instance

Arrow functions do not provide their own this binding:

In arrow functions, this retains the value of the enclosing lexical context's this. [source]

Change your code to the following:

UserSchema.pre('save', function (next) {
    const user = this;
    // ... code omitted
});

2. Not handling duplicate key MongoError

The request might fail with MongoError: E11000 duplicate key error collection since email field is unique. You are ignoring such fail and since stored in your user.save() is undefined the response from the server is going to be an empty object.

To fix this issue you need to add a handler in the following code:

user.save((err, stored) => {
  if (err) {
    throw err; // some handling
  }
  res.status(200).send({user: stored});
});
gurisko
  • 1,172
  • 8
  • 14