How to connect Express js with mongodb

Prerequisite tutorial:

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