DEV Community

Cover image for How to Connect Mongo db with Node JS & Express JS
badcaptain0001
badcaptain0001

Posted on

How to Connect Mongo db with Node JS & Express JS

Setting Up a Node.js Project
Initialize Node.js Project: Create a new folder for your project and run npm init to initialize a new Node.js project.

Install Dependencies

npm install express mongoose
Enter fullscreen mode Exit fullscreen mode

Connecting MongoDB with Mongoose
Set up a basic Express application in your index.js file:

const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
require("./dbconnection.js")

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Set up a Db connection file dbconnection.js file:

const mongoose = require("mongoose");
const express = require("express");
require("dotenv").config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.once("open", (_) => {
  console.log("Database connected:", process.env.MONGODB_URI);
});

db.on("error", (err) => {
  console.error("connection error:", err);
});
Enter fullscreen mode Exit fullscreen mode

by replacing process.env.MONGODB_URI with you own url

Go to terminal and type npm start

npm start
Enter fullscreen mode Exit fullscreen mode

Congratulatios! you db has been connected now you can start playaround it

Top comments (0)