How to encrypt passwords (or other data) before saving it in MongoDB

Hi Friends,

Pheew.. Its been a very, very long time since I came out with a post. I really apologize; I was stuck in office work and was also busy learning and experimenting with stuff like AngularJS, MongoDB and nodeJS.

Anyway today I will show you how to encrypt passwords or any other data that you save in MongoDB.

Lets get started. As usual I will break it down and give you simple steps to do it.

Step 1:

First of all you need to know a little bit about nodeJS. Its awesome and easy to learn. Install the node package manager (npm) onto your computer and open up terminal. Then create a new directory and cd into the directory. Once you are in  give the below command.

npm init

Fill in the particulars as required and hit enter. Then give this command.

npm install mongoose –save-dev

Mongoose is an elegant mongodb object modeling for node.js. It is an object data mapping solution. When you want to keep data organized and structured mongoose would help you a lot.

Type the below command and start mongo.


(You can also give the path as mongod –dbpath <path to directory where you want to save data>)

Now create a file called index.js in the same directory and type in the below code.

Now if you save the file and then give the below command

node index.js

You would see a message saying Connection to DB successful.

Step 2:

Next comes Schemas. Schemas are nothing but skeletons of the data you are going to store in your db.

For a simple example let us use the below fields

Name –> String.

Password –> String.

The code for defining this would be as follows

The create a model for this schema using which we could save data into the db as shown below:

Now prepare some test data and trying saving this.

This would actually save the data and then print the data stored as shown below:

Success: { __v: 0,
name: ‘admin’,
password: ‘test123’,
_id: 5523099b8e8c8e1026e5bf9e }

Now comes the encryption part.

Step 3:

To encrypt the password before it is getting saved we are going to use a package called bcrypt. If you would like to know more about bcrypt I would suggest this article.

To install bcrypt give the below command

npm install bcrypt –save-dev.

We will also be using salt to resist brute-force. From the mongodb blog

“the purpose of the salt is to defeatrainbow table attacks and to resist brute-force attacks in the event that someone has gained access to your database. bcrypt in particular uses a key setup phase that is derived from Blowfish.

All you need to know about that is that the key setup phase is very computationally expensive, which is actually a good thing when trying to thwart brute-force attacks. How expensive depends on how many rounds or iterations the key setup phase uses – this is where our SALT_WORK_FACTOR comes into play.”

Before we move on we need to know something about middlewares. From the moongoosejs docs,

“Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions.”

In our scenario we will use the pre hook and write a function to encrypt the password as shown below.

Also don’t forget to add the below two lines at the top.

After this the complete index.js file would look as shown below:

Go to terminal and then give the below command:

node index.js

Our password is first encrypted and then saved.

If everything is fine you would get the below message:

Connection to DB successful.
Success: { __v: 0,
name: ‘admin’,
password: ‘$2a$10$v0ygTGmi.ViIeohjP5x5EuwYIrWBKw1vSS8Xp8dk0S.cSbtN7mx1q’,
_id: 5523099b8e8c8e1026e5bf9e }

As you can see our password is now encrypted.

Hope this helps you out. Please don’t hesitate to ask for help if needed. Have a great day. Peace.. :) :)

Liked it? Take a second to support admin on Patreon!
  • Pingback: REST api authentication for your Ionic 2 app – Part 1 | T-Pub :)()

    • admin

      Hi Suhas,
      Thanks for the help bro.

  • Suhas Chikkanna


    I think there is a correction in the article to be done. To install bcrypt, I think we have to run this below command:-

    npm install bcrypt –save-dev

    instead of

    node install bcrypt –save-dev

  • DaMair

    i wanted to implement your auth service for angular 2 and the front end is working great!(thx for the great How to video!) but could you make a video for the MongoDB database? i think i make something wrong… i created a db and inserted some users but when i start the server.js i get the following error:

    C:UsersDavidDesktopDIPL ARBEITionic-authentication-master>node server.js
    C:UsersDavidDesktopDIPL ARBEITionic-authentication-masternode_modulesbindingsbindings.js:83
    throw e

    Error: %1 ist keine zulässige Win32-Anwendung.(that means its not a valid win32 application in german)
    \?C:UsersDavidDesktopDIPL ARBEITionic-authentication-masternode_modulesbcryptbuildReleasebcrypt_lib.node
    at Error (native)
    at Object.Module._extensions..node (module.js:434:18)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at bindings (C:UsersDavidDesktopDIPL ARBEITionic-authentication-masternode_modulesbindingsbindings.js:76:44)
    at Object. (C:UsersDavidDesktopDIPL ARBEITionic-authentication-masternode_modulesbcryptbcrypt.js:3:35)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object. (C:UsersDavidDesktopDIPL ARBEITionic-authentication-mastermodeluser.js:3:14)
    at Module._compile (module.js:409:26)

    i hope you can help me with it i try it since 2 days 😀

  • Ramya

    Hi…its working superb
    can you please tell me how to store password in elasticsearch db using nodejs
    it is very helpful to me to learn

  • Ramya

    1.How to compare the hashes using the same bcrypt

    • OswaldJon

      Hi, You need to use, existingHash, function(err, res){
      //res === true