How To Connect MongoDB in Express Application


In this article, i will share with you how to connect the MongoDB database to your express application. you just need to follow the steps.

Step - 1 : Install express and mongoose

First of all, install express and mongoose by running the following npm command in your application's root directory.

npm init -y

npm install mongoose express

Step - 2 : Create index.js File

Create a file name called index.js.

const express = require("express")
const Mongoose = require("mongoose")
const app = express()
mongoose.connect("mongodb://localhost:27017/testdb", {
  useNewUrlParser: "true",
mongoose.connection.on("error", err => {
  console.log("err", err)
mongoose.connection.on("connected", (err, res) => {
  console.log("mongoose is connected")
const PORT = 3000
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)

i hope you like this article.