How to connect Express js with MongoDB

Prerequisite tutorial:

  1. Install Nodejs:
version check:
node -v

2. Install express.js, mongoose, morgan and nodemon

mkdir blog_expressjs
cd blog_expressjs
npm init -y //Initialise and Configure Our Project
npm i express mongoose morgan dotenv cors --save
// express install
// mongoose: mongodb install
// morgan: for show log
//cors: cors install
npm i -D nodemon //server restart when some change

3. package.json

Add ‘“start”: “nodemon app.js”

"name": "blog_expressjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js"
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.11.8",
"morgan": "^1.10.0"
"devDependencies": {
"nodemon": "^2.0.6"

When I will write the following command ‘’npm start’’ than ‘’npm nodemon app.js’’ will be run.

4. app.js

const express = require('express')
const cors = require("cors");
const morgan = require('morgan') //medillower function
const mongoose = require('mongoose')
const app = express() //route handaling,controller,templet engine,middlewareapp.use(morgan('dev')) //middleware
app.use(express.urlencoded({extended: true})) // for get form data
app.get('/', (req, res) => {
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
app.listen(4545, () => {
.catch(e => {

Mongoose official website.(use this following tool we can easily connect with mongodb).

sudo systemctl status mongodmongodb-compass

5. Run your project:

npm start



Senior Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store