How to Connect Node js to MongoDB using Mongoose Tutorial?

29-Nov-2022

.

Admin

How to Connect Node js to MongoDB using Mongoose Tutorial?

Hello Friends,

Mongoose.js connects your MongoDB clusters or collections with your Node.js app. It enables you to create schemas for your documents. Mongoose provides a lot of functionality when creating and working with node.js.

MongoDB is a document database built on a scale-out architecture that has become popular with developers of all kinds who are building scalable applications using agile methodologies. MongoDB was built for people who are building internet and business applications who need to evolve quickly and scale elegantly.


Step 1: Create Node JS App

Create Node js express app; So, execute the following command on terminal:

mkdir my-app

cd my-app

npm init -yes

Step 2: Install Mongoose and Body Parser Module

Install mongoose s and body-parser modules into your node js express application by executing the following command on the command prompt:

npm install mongoose express body-parser

body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and makes it available under req.body property. In other words, it simplifies incoming requests.

Step 3: Create Server.js File

Create Server.js and import the above installed modules in it. So visit your app root directory and create Server.js and validate fields; as follows:

const express = require("express")

const mongoose = require("mongoose")

const bodyParser = require("body-parser")

const app = express()

const PORT = 3000

app.listen(PORT, () => {

console.log(`app is listening to PORT ${PORT}`)

})

Step 4: Connect App to MongoDB

Connect mongoose to local MongoDB instance with DB name as testDB; so add the following code into server.js file:

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")

})

Step 5: Start App Server

Open your command prompt and execute the following command to run the node js express file upload application:

//run the below command

node sever.js

I hope it can help you...

#Node JS