Authentication with Nodejs and mongoDB - Part 2
Tags: mongodb, node, authentication, tutorial
Published: 2020-09-20 12:52:57

In the [previous part](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-1-10pn), we setup our mongoDB database and connected it to our nodejs app.

In this part, we will setup the model and make a ``register`` endpoint that will accept input and hash the password using [``bcrypt``](https://www.npmjs.com/package/bcrypt). Let's get started.

## Starter Project
If you are not coming from the previous tutorial, then you can get the starter project from [here](https://github.com/EBEREGIT/auth-backend/tree/db-config)

## Creating Users Model
* Create a file in the ``db`` folder and name it ``userModel``
* In the file, require ``mongoose``

```javascript

const mongoose = require("mongoose");

```
* Create a constant (``UserSchema``) and assign it the mongoose schema like so

```javascript

const UserSchema = new mongoose.Schema({})

```

* In the schema, enter the 2 fields we need (``email`` and ``password``) and assign an empty object to them like so:

```javascript
const UserSchema = new mongoose.Schema({
  email: {},

  password: {},
})

```

* Let's now specify how the fields should look like or work by adding some [mongoose option](https://mongoosejs.com/docs/guide.html)

```javascript

email: {
    type: String,
    required: [true, "Please provide an Email!"],
    unique: [true, "Email Exist"],
  },

  password: {
    type: String,
    required: [true, "Please provide a password!"],
    unique: false,
  },

```
* Finally, let's export ``UserSchema`` with the following code

```javascript

module.exports = mongoose.model.Users || mongoose.model("Users", UserSchema);

```
*The code above is saying: "create a user table or collection if there is none existing with that name"*

> Now we have completed our model for the user, the ``user`` collection is now ready to receive the data we will pass in.

## Register User Endpoint
* Install [bcrypt](https://www.npmjs.com/package/bcrypt). This will be used to hash the password we will receive from the users

```javascript

npm install --save bcrypt

```

* Require ``bcrypt`` at the top of the ``app.js`` file 

```javascript

const bcrypt = require("bcrypt");

```

* Require the ``userModel`` just below the line where we required our database

```javascript

const User = require("./db/userModel");

```

* We will create a ``register`` endpoint just before the ``module.exports = app;`` line

```javascript

app.post("/register", (request, response) => {

});

```

* We will hash the password before saving the email and password into the database. So let's hash the password with the following code:

```javascript

bcrypt.hash(request.body.password, 10)
  .then()
  .catch()

```

*The code above is telling ``bcrypt`` to hash the ``password`` received from ``request body`` 10 times or salt rounds*

*If the hash is successful, we will continue in the ``then`` block and save the ``email`` and ``hashed password`` in the database else we will return an error in the ``catch`` block*

* In the ``catch`` block, let's return an error like so:

```javascript

   .catch((e) => {
      response.status(500).send({
        message: "Password was not hashed successfully",
        e,
      });
    });

```

* In the ``then`` block, let's save the data we have now. We create a new instance of the ``userModel`` and collect the updated data like so

```javascript

.then((hashedPassword) => {
      const user = new User({
        email: request.body.email,
        password: hashedPassword,
      });
});

```

* Next, save the data. Still in the ``then`` block, we have:

```javascript

user.save()

```
*And that is it. If you stop at this point, it's all good. It saves but no feedback.*

* To get a feedback, let's use a ``then...catch...`` block

```javascript

     user.save().then((result) => {
        response.status(201).send({
          message: "User Created Successfully",
          result,
        });
      })
      .catch((error) => {
        response.status(500).send({
          message: "Error creating user",
          error,
        });
      });

```
Finally, our ``register`` endpoint now looks like this:

```javascript

// register endpoint
app.post("/register", (request, response) => {
  // hash the password
  bcrypt
    .hash(request.body.password, 10)
    .then((hashedPassword) => {
      // create a new user instance and collect the data
      const user = new User({
        email: request.body.email,
        password: hashedPassword,
      });

      // save the new user
      user
        .save()
        // return success if the new user is added to the database successfully
        .then((result) => {
          response.status(201).send({
            message: "User Created Successfully",
            result,
          });
        })
        // catch erroe if the new user wasn't added successfully to the database
        .catch((error) => {
          response.status(500).send({
            message: "Error creating user",
            error,
          });
        });
    })
    // catch error if the password hash isn't successful
    .catch((e) => {
      response.status(500).send({
        message: "Password was not hashed successfully",
        e,
      });
    });
});

```

## Testing our Endpoint
* Start your server in the terminal if you have not done so

![Start your terminal](https://dev-to-uploads.s3.amazonaws.com/i/oo9g5y5j9tiv1t8cn91y.JPG)

* Go to your postman and test like mine below

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/oe3ay8c5gz2c24cpw1cr.JPG)

* Go to your mongoDB Atlas. Click on ``Collections`` and you should see the data you just added like mine below

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4znw7bw783l1hx1i3rms.JPG)

*Congratulations on Attaining this feet*

### Conclusion
This was part 2 of this authentication series. It has shown us clearly how easy it is to add a user to a mongoDB database after hashing the password.

All codes are [here](https://github.com/EBEREGIT/auth-backend/tree/register-endpoint)

{% github eberegit/auth-backend no-readme %}

Next, we will look that how to [create a login and generate a toke using Jasonwebtoken (JWT)](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-3-3mic).

Stick with me. I will see you soon.