DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

Authentication with Nodejs and mongoDB - Part 2

In the previous part, 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. Let's get started.

Starter Project

If you are not coming from the previous tutorial, then you can get the starter project from here

Creating Users Model

  • Create a file in the db folder and name it userModel
  • In the file, require mongoose

const mongoose = require("mongoose");

Enter fullscreen mode Exit fullscreen mode
  • Create a constant (UserSchema) and assign it the mongoose schema like so

const UserSchema = new mongoose.Schema({})

Enter fullscreen mode Exit fullscreen mode
  • In the schema, enter the 2 fields we need (email and password) and assign an empty object to them like so:
const UserSchema = new mongoose.Schema({
  email: {},

  password: {},
})

Enter fullscreen mode Exit fullscreen mode
  • Let's now specify how the fields should look like or work by adding some mongoose option

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

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

Enter fullscreen mode Exit fullscreen mode
  • Finally, let's export UserSchema with the following code

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

Enter fullscreen mode Exit fullscreen mode

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. This will be used to hash the password we will receive from the users

npm install --save bcrypt

Enter fullscreen mode Exit fullscreen mode
  • Require bcrypt at the top of the app.js file

const bcrypt = require("bcrypt");

Enter fullscreen mode Exit fullscreen mode
  • Require the userModel just below the line where we required our database

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

Enter fullscreen mode Exit fullscreen mode
  • We will create a register endpoint just before the module.exports = app; line

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

});

Enter fullscreen mode Exit fullscreen mode
  • We will hash the password before saving the email and password into the database. So let's hash the password with the following code:

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

Enter fullscreen mode Exit fullscreen mode

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:

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

Enter fullscreen mode Exit fullscreen mode
  • 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

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

Enter fullscreen mode Exit fullscreen mode
  • Next, save the data. Still in the then block, we have:

user.save()

Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

Finally, our register endpoint now looks like this:


// 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,
      });
    });
});

Enter fullscreen mode Exit fullscreen mode

Testing our Endpoint

  • Start your server in the terminal if you have not done so

Start your terminal

  • Go to your postman and test like mine below

Alt Text

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

Alt Text

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

GitHub logo EBEREGIT / auth-backend

This tutorial teaches how to create authentication for a user using nodejs and mongoDB

Next, we will look that how to create a login and generate a toke using Jasonwebtoken (JWT).

Stick with me. I will see you soon.

Top comments (3)

Collapse
 
bralexsvg profile image
Adam Alex

Please boss my newly created data is not appearing in my cluster
It says query result 0
Please help me out

Collapse
 
ebereplenty profile image
NJOKU SAMSON EBERE

I hope the call made things clearer.

It is important to pay attention to every detail. That is why I make the tutorial step by step. I also make indicators on the screenshots.

Please Follow these indicators

Collapse
 
varunthaker profile image
varunthaker

Hey Njoku,
For the code, user is created and saved to database but it does not store the hashed password.
Can you please help me on this?