Back to Courses

World's Best MERN Stack Course

MERN Stack #7: Connecting Backend with MongoDB Database (Node.js + Mongoose Connection)

Welcome, We'll show you how to write the connection code using Mongoose, call it in your server.js file, and check your local database for data. This step-by-step guide will boost your MERN stack skills and ensure a solid link between your backend and database. Let's build something great together!

utils / db.js

const mongoose = require("mongoose");

const URI = "mongodb://127.0.0.1:27017/mern_admin_panel";

const connectDb = async () => {
  try {
    await mongoose.connect(URI);
    console.log("connection successful to DB");
  } catch (error) {
    console.error("database connection fail");
    process.exit(0);
  }
};

module.exports = connectDb;

server.js

const express = require("express");
const app = express();
const router = require("./routes/auth-route");
const connectDb = require("./utils/db");

// Mount the Router: To use the router in your main Express app, you can "mount" it at a specific URL prefix
app.use("/api/auth", router);

const PORT = 5000;

connectDb().then(() => {
  app.listen(PORT, () => {
    console.log(`server is running at port: ${PORT}`);
  });
});