Documentation
Source Code
lib
database.ts(Mongoose)

database.ts(Mongoose)

This module exports a single function connectToDatabase that helps you easily connect to a MongoDB database using the popular Mongoose library.

Usage

  1. Import the connectToDatabase function from this module:
import { connectToDatabase } from "path/to/db";
  1. Call the connectToDatabase function to establish a connection to the MongoDB database:
connectToDatabase();

That's it! The function will automatically connect to the database specified by the DATABASE_URL and DATABASE_NAME environment variables.

Code

import mongoose from "mongoose";
 
let isConnected: boolean = false;
 
export const connectToDatabase = async () => {
  mongoose.set("strictQuery", true);
 
  if (!process.env.DATABASE_URL) {
    return console.log("DATABASE_URL must be defined");
  }
 
  if (isConnected) {
    console.log("=> using existing database connection");
    return;
  }
 
  try {
    await mongoose.connect(process.env.DATABASE_URL, {
      dbName: process.env.DATABASE_NAME,
    });
    isConnected = true;
    console.log("MongoDB connection is Made!");
  } catch (error) {
    console.log("=> error while connecting to database:", error);
  }
};

How it Works

  1. The connectToDatabase function first checks if the DATABASE_URL environment variable is defined. If not, it logs an error message.

  2. If a database connection already exists, the function simply logs a message and returns without attempting to establish a new connection.

  3. If no connection exists, the function uses Mongoose's connect method to establish a new connection to the database specified by the DATABASE_URL environment variable. It also sets the dbName option to the value of the DATABASE_NAME environment variable.

  4. If the connection is successful, the function sets the isConnected flag to true and logs a success message.

  5. If an error occurs during the connection process, the function logs the error message.

Environment Variables

Make sure to set the following environment variables before running your application:

  • DATABASE_URL: The connection string for your MongoDB database.
  • DATABASE_NAME: The name of the database you want to connect to.