DEV Community

Tanzim Ibthesam
Tanzim Ibthesam

Posted on • Updated on

Node Express CRUD with Mongoose,JWT authentication,authorization

Here we will make a CRUD with REST API along with its authentication.Express.js is unopinionated means everyone can have their own way of doing things which is quite different from a strict framework.
If you are using VS code and type Cntrl+` to open the terminal and write npm init -y
It will create a pacakge.json file for you on the left hand side
At first you need to install express and mongoose.
npm install express && npm install mongoose
If you go to package.json file you can see
In our depencies you have got your express and mongoose installed to check whether a package has been installed go package.json. These are pretty basic stuffs but will help a begiiner a lot.
you will create a file called app.js
in app.js
These are the thigs you will initially write in app.js file here you will initialize express
go to terminal type node app.js
Now we can see that the server is initialized on port 5000. The port can be anything 5000,6000,8000.
But the problem is we need to run it each and every single time when there is any change. As a result we need to install nodemon
npm install nodemon Then if we go to our package.json file we will see
noe if we want to use nodemon we can use the scripts in package.json file
Now we can go to your terminal and run npm start

Now you dont need to run node app.js nodemon will restart everytime there is a change
Connection with MongoDB through mongoose
If you dont have MongoDb installed on your system please install it first. Here you creating a new database we will use Robo3t here
if you go to Robo 3t you can see
If you click connect you can see

It will look something like this

From here you will see a modal like this you will named your databse and see create

If you have done everything correctly you will see name of the databse you have created on the left

We can use .env files for that we need to install a new package



If everything is alright we can now we can see it running

We can install npm install dotenv to keep database name in an env file
In .env file
In app.js file

This is not mandatory but a good practice
Let us get the router fixed we need to create a new file called router.js you can set all routes inside app.js but its better to have a separate route file now if we create router.js


In app.js
const allRouter=require('./routes')

Now we need 2 parts 1 is the model and other is the controller
In Model part there will be the database and controller part will have the logic

Create a new folder model/Post.js
here we see we can that we want to add two fields to posts collection title and description

CRUD part
In routes.js
Import PostsController
const PostsController=require("./controller/Posts");
Post route'/posts/create',PostsController.createPost);
Import Post Model on top
in controller/Posts.js
Test in Postman
Make sure in headers Content type is set to application/json
Testing post request

We can clearly see its successfull giving us a status code of 200

In router.js

In controller/Posts.js

Postman test
If we also check in Robo 3T

Now we can say that it has been successfully inserted onto database.
In router.js
In controller/Posts.js

Test in Postman
Here you can get id from databse using Robo3T or just by using get requests to get all posts
Now we see from where we can get the id and get a single post

In router.js
//Updating a single post

In controller/Posts.js
Testing in postman
The same way we get id like shown with getting id of a single post
In router.js
//Delete a post

In controller/Posts.js
Testing in postman
We will get the individual post and delete
While Updating you most likely will get an warning
Mongo Db update warning
For resolving the warning go to app.js
useFindAndModify: false
Mongo Update warning resolved

API Authentication,authorization with JWT
Now we will do authentication using email and password only. Remember JWT is used for authorization not authentication
Create a new model in model/User.js
IN User.js
In this case
model user
Here we are including email,password and token.

In controller folder we will create a new file called Auth.js
We need to import User model at the top
User Model

In router.js
//signup route'/signup',AuthController.signup) we need to import AuthController at the top
const AuthController=require("./controller/Auth")
In controller/Auth.js
We need to install a package called bcyrpt
Signup method in Auth.js

Here is signup we need to use bcrypt to hash the password as we all know passwords cant be stored in plain text
Testing in Postman
As we see the password is hashed and status is ok
Signin Route
In router.js'/signin',AuthController.signin);
In signin route after checking credentials a token needs to be generated.Remember Token is for authorization not authentication. We set the secret key on top the secret key can be set in .env file remember the secret key must be secret.
Testing in Postman

We will use a pacakge named express-jwt for installing npm install express-jwt.
Creating a middleware
A middleware can be termed as something between a request and response.If we want to protect any route that users who only have token can enter those routers.
in controller/Auth.js
signedIn middleware
Route test with middleware
In router.js on top
const {isSignedIn}=require("./controller/Auth");
Route with isSignedIn
res.send("A protected route")

Testing in Postman
Here if we try to access this route without token we get this error 401 forbidden means without token you cant access this route.
test with token

Here we need to go to header part of the token include Authorization in header.In value of authorization header we need to write Bearer give a space before the token and then copy and paste the token authorization value
If you go to jwt and test your jwt you will see you get all your info
jwt. Here header is the type which is JWT the signature is the token and payload is the email and id.So that's all for this blog. Hopefully you will be able to grasp the concepts of Node,Express,Jwt,authentication,authorization here.

Discussion (3)

gochev profile image
Nayden Gochev

Super random question @tanzimibthesam but I noticed you are using windows.

However what is the FONT and SIZE you are using in the screenshots with the darkula theme.
For example ?

It looks good :) thanks for the info

tanzimibthesam profile image
Tanzim Ibthesam Author • Edited

Thanks Nayden its not Dracula its known as Teacher theme Dark
The Font name is Consolas, 'Courier New', monospace
Here is the link of the

gochev profile image
Nayden Gochev

my consoles size 14 doesn't look like that hmmmm but thanks :)