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

What is the Event Loop in javascript?

Curry away in React

How to customize a Gatsby Netlify CMS starter

Exporting data in excel file in Node.js

Restaurant Is Now Delivering: a Facebook Bot in Node.js

Scale Your Home Goods Venture In 2022 With Furniture Marketplace App Development

4 Best Practices for Large Scale Vue.js Projects

Service Account Integrations to access and modify files over drive from your angular application.

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

Node Js With MongoDB

Aggregation Framework In MongoDB

NoSQL Database | MongoDB

Deploy Nodejs Backend App on Digital Ocean