mongoose Mongoose Middleware Middleware to hash user password before saving it


This is an example of Serial Document Middleware

In this example, We will write a middleware that will convert the plain text password into a hashed password before saving it in database.

This middleware will automatically kick in when creating new user or updating existing user details.

FILENAME : User.js

// lets import mongoose first
import mongoose from 'mongoose'

// lets create a schema for the user model
const UserSchema = mongoose.Schema(
    name: String,
    email: { type: String, lowercase: true, requird: true },
    password: String,

 * This is the middleware, It will be called before saving any record
UserSchema.pre('save', function(next) {

  // check if password is present and is modified.
  if ( this.password && this.isModified('password') ) {

    // call your hashPassword method here which will return the hashed password.
    this.password = hashPassword(this.password);


  // everything is done, so let's call the next callback.


// lets export it, so we can import it in other files.
export default mongoose.model( 'User', UserSchema );

Now every time we save a user, This middleware will check if password is set and is modified (this is so we dont hash users password if its not modified.)


import express from 'express';
import mongoose from 'mongoose';

// lets import our User Model
import User from './User';

// connect to MongoDB
mongoose.Promise = global.Promise;

let app = express();
/* ... express middlewares here .... */ '/', (req, res) => {

    req.body = {
      name: 'John Doe',
      email: '',
      password: '!trump'

  // validate the POST data

  let newUser = new User({
    password: req.body.password,
  }); ( error, record ) => {
    if (error) {
        message: 'error',
        description: 'some error occoured while saving the user in database.'
    } else {
        message: 'success',
        description: 'user details successfully saved.',
        user: record


let server = app.listen( 3000, () => {
    console.log(`Server running at http://localhost:3000` );