Using MongoDB with ExpressJS - Part 1 (Setting Up Express)
Power-packed Express with MongoDB for solid Backend Service
This would be a detailed article on how MongoDB can be used with express to make a full-fledged backend service and serve any frontend application.
MongoDB Atlas makes it very useful to connect to a database and perform operations on it! First of all, let us go through some basic setup for express. Follow the below steps to set up an express server.
ExpressJS Setup:-
- Type
npm init
in the terminal to have thepackage.json
file setup. - Type
npm install express nodemon
to have express installed and nodemon helps to refresh the server rather than to stop and run again. - Now just go to the package.json file and in scripts clear everything and type a start command:-
"start": "nodemon app.js"
- Now make an app.js file where all your express app will reside
- Add these lines of code given below for initializing the app.
const express = require('express');
const app = express();
app.listen(3000);
Now after initialization, we can now make routes have some URL. Let me show an example of an URL in express:-
app.get('/',(req,res)=>{
res.send("hello world");
})
We can make the routes as these and have different functions as needed. As we are building a crud app we can have a post, add, delete, and update URLs for the express app. Before moving to URLs, one thing I want to stress upon is the as we have written above app.get above we have more such methods like:=
app.get
- to get any information, can be used when retrieving the data from the databaseapp.post
- to post any information, can be used when we insert some data in the databaseapp.delete
- when we want to delete some stuff in the databaseapp.patch
- to update the data in the database
Now let's make some basic routes and add in the express app!
app.get('/retrieve',(req,res)=>{
res.send("We will retrieve data from this URL");
app.post('/add',(req,res)=>{
res.send("Add the data");
app.delete('/del',(req,res)=>{
res.send("delete the data");
app.patch('/update',(req,res)=>{
res.send("Update");
Now we have finished setting up the express server. You can just spin the server using the command npm start
and hit the routes at localhost:3000/{URL}
where URL can be any route we have defined in the above app.js file.