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 ituserModel
- In the file, require
mongoose
const mongoose = require("mongoose");
- Create a constant (
UserSchema
) and assign it the mongoose schema like so
const UserSchema = new mongoose.Schema({})
- In the schema, enter the 2 fields we need (
email
andpassword
) and assign an empty object to them like so:
const UserSchema = new mongoose.Schema({
email: {},
password: {},
})
- 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,
},
- Finally, let's export
UserSchema
with the following code
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. This will be used to hash the password we will receive from the users
npm install --save bcrypt
- Require
bcrypt
at the top of theapp.js
file
const bcrypt = require("bcrypt");
- Require the
userModel
just below the line where we required our database
const User = require("./db/userModel");
- We will create a
register
endpoint just before themodule.exports = app;
line
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:
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:
.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 theuserModel
and collect the updated data like so
.then((hashedPassword) => {
const user = new User({
email: request.body.email,
password: hashedPassword,
});
});
- Next, save the data. Still in the
then
block, we have:
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
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:
// 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
- Go to your postman and test like mine below
- Go to your mongoDB Atlas. Click on
Collections
and you should see the data you just added like mine below
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
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)
Please boss my newly created data is not appearing in my cluster
It says query result 0
Please help me out
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
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?