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.