Node js Connect to MongoDB using Mongoose Tutorial

In this tutorial, you will learn how to connect the MongoDB database in the Node Express js application using Mongoose.

How to Connect MongoDB with Node js Express Application using Mongoose

Steps to connect mongoDB database server:

Step 1 – Create Node JS App

Create Node js express app by running the following command on cmd:

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 running the following command on command prompt:

npm install mongoose express body-parser

Step 3 – Create Server.js File

Create a Server.js file, and import the above-installed modules in it:

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 the local MongoDB instance with db name testdb, and add the following code connection code in 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 – Test Application

Open your command prompt and run the following command to start application server:

node sever.js

Conclusion

That’s it, you have learn how to connect mongodb using mongoose with node js express application.

Recommended Node Js Tutorial

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *