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
- Import the
connectToDatabase
function from this module:
import { connectToDatabase } from "path/to/db";
- 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
-
The
connectToDatabase
function first checks if theDATABASE_URL
environment variable is defined. If not, it logs an error message. -
If a database connection already exists, the function simply logs a message and returns without attempting to establish a new connection.
-
If no connection exists, the function uses Mongoose's
connect
method to establish a new connection to the database specified by theDATABASE_URL
environment variable. It also sets thedbName
option to the value of theDATABASE_NAME
environment variable. -
If the connection is successful, the function sets the
isConnected
flag totrue
and logs a success message. -
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.