How to connect Express js with mongodb

Prerequisite tutorial:

  1. Install Nodejs:
version check:
node -v

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

express.js(express js install)

mongoose(mongodb install)

morgan(for show log)

nodemon(server restart when some change occur)

mkdir blog_expressjs
cd blog_expressjs
npm init -y //Initialise and Configure Our Project
npm i express mongoose morgan
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 morgan = require('morgan') //medillower function
const mongoose = require('mongoose')
const express = require('express')
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.use(express.json())
app.get('/', (req, res) => {
console.log("peyas")
res.send("peyas")
})
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
app.listen(4545, () => {
console.log('Connected')
})
})
.catch(e => {
console.log(e);
})

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

sudo systemctl status mongodb

mongodb-compass

5. Run your project:

npm start
http://localhost:4545/

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Build Your Next AR/VR Web App Using JavaScript

How to create a loading screen for any SwiftUI app with just two modifiers — Redacted and Shimmer

Web Application for Pub Crawl Planning

Let’s Understand Some OOP ( Object Oriented Programming ) terms easily.

After A Year Of Using NodeJS In Production

When an extended class replaces the base class

PDF Download> A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your…

An In-Depth Exploration of the Array.flat() Function

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
Safaetul Ahasan

Safaetul Ahasan

Software Engineer

More from Medium

Application Framework with node.js

Axios and Express

The Top 4 Reasons for Using Node.js

Node Js With MongoDB