Database Integration MongoDB

Last Updated : Oct 2026


We connect our application to a database to store and retrieve data.We only need to install an appropriate database driver for our chosen database and configure it to work with our application.

In This Tutorial, We will cover some of the popular database connectivity.

  • MongoDB
  • MySQL
  • PostgreSQL

So let's get started with MongoDB.

MongoDB

Connecting Express to MongoDB with Mongoose

To get started with real code, install the required packages in your Express project:

Step 1: Install Dependencies

npm install mongoose dotenv

Step 2:Environment Configuration (.env)

Create a .env file in your project root to store your database connection string securely:

PORT=3000
MONGO_URI=mongodb://127.0.0.1:27017/my_express_db

Step 3: Database Connection

For Better Structure, Create a folder called lib in the root of your project and create a db.js file in it:

import { connect } from "mongoose";

let isConnected = false;

export const connectDb = async () => {
  try {
    if (isConnected === true) return;
    await connect(process.env.MONGO_URI!);
    isConnected = true;
    console.log("Connected to MongoDB");
  } catch {
    console.error(`Error connecting to MongoDB: ${error.message}`);
    process.exit(1); // Exit process with failure
  }
};

Step 4: Server Setup (server.js)

import express from "express";
import dotenv from "dotenv";
import { connectDb } from "./lib/db";

dotenv.config();

const app = express();

app.use(express.json());

connectDb();

app.get("/", (req, res) => {
  res.send("API is running...");
});

app.listen(process.env.PORT, () => {
  console.log(`Server running on http://localhost:${process.env.PORT}`);
});

Step 5: Start the Server

node --watch server.js

You should see the following message in the console:

Server running on http://localhost:3000
Connected to MongoDB

Basic CRUD Operations

The Schema & Model Layer

A Schema defines the structure, data types, and validation rules for documents in a MongoDB collection. A Model is a wrapper around the schema that provides the direct interface for database queries.

import mongoose from "mongoose";

// 1. Schema Definition (Data rules & types)
const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Name is required"],
      trim: true,
    },
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true, // Creates a unique index in MongoDB
      lowercase: true,
    },
    age: {
      type: Number,
      min: [18, "Must be at least 18 years old"],
    },
    role: {
      type: String,
      enum: ["user", "admin"],
      default: "user",
    },
  },
  {
    timestamps: true, // Automatically manages createdAt and updatedAt fields
  },
);

// 2. Model Creation (Database interface)
// 'User' maps to the 'users' collection in MongoDB
export const User = mongoose.models?.User || mongoose.model("User", userSchema);

Create a User

async function createUser(userData) {
  // Option 1: Using Model.create()
  const newUser = await User.create(userData);

  // Option 2: Instantiating and saving
  // const user = new User(userData);
  // const newUser = await user.save();

  return newUser;
}

Read a User

// Reading documents from MongoDB
async function getUsers() {
  // Find all users where role is 'user', select specific fields, and sort
  const users = await User.find({ role: "user" })
    .select("name email role") // Includes only name, email, role
    .sort({ createdAt: -1 }); // Newest first

  // Find a single user by primary ID (_id)
  const singleUser = await User.findById("65a123456789abcdef012345");

  // Find one matching specific criteria
  const userByEmail = await User.findOne({ email: "tukkalearn@example.com" });

  return { users, singleUser, userByEmail };
}

Update a User

// Updating documents in MongoDB
async function updateUser(userId, updateData) {
  // findByIdAndUpdate takes (id, updateFields, options)
  const updatedUser = await User.findByIdAndUpdate(userId, updateData, {
    new: true, // Return the updated document instead of the original
    runValidators: true, // Enforce Schema validations on updates
  });

  return updatedUser;
}

Delete a User

// Deleting documents from MongoDB
async function deleteUser(userId) {
  // Deletes document matching the _id
  const deletedUser = await User.findByIdAndDelete(userId);

  // Bulk delete matching conditions
  // await User.deleteMany({ role: 'user', age: { $lt: 18 } });

  return deletedUser;
}

Note: Above functions are just examples, you can use them as per your needs.


Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR