🚀 Beta mode be careful of the bugs
Mongo-db

Database

Steps to set up a MongoDB database in your project.

Overview

MongoDB is a NoSQL database that stores data in a JSON-like format. It is a popular choice for big data and real-time web applications.

Database Connection Setup

Installation

To install MongoDB, you can use the following command:

npm install mongodb

Database Setup

To connect to the MongoDB database, follow these steps:

  1. Create a new file called database.js in your project root.
  2. Path to the file: ./lib/database.js
  3. Add the following code to the file:
import mongoose from "mongoose";
 
type ConnectionObject = {
  isConnected?: boolean;
};
 
const mongoUri = process.env.MONGO_URI;
 
if (!mongoUri) {
  console.error("Please provide MongoDB URI");
}
 
const connection: ConnectionObject = {};
 
async function dbConnect(): Promise<void> {
  if (connection.isConnected) {
    console.log("Already connected to database");
    return;
  }
 
  try {
    const db = await mongoose.connect(mongoUri!, {});
    connection.isConnected = db.connections[0].readyState === 1;
    console.log("Database connected successfully");
  } catch (error) {
    console.error("Database connection failed", error);
    process.exit(1);
  }
}
 
export default dbConnect;

Example with Mongoose

To connect to the MongoDB database using Mongoose, create a user model:

import mongoose, { Schema } from "mongoose";
 
export interface User {
  _id?: string;
  username: string;
  email: string;
  password?: string;
  role: "user" | "admin";
  createdAt?: Date;
}
 
const UserSchema: Schema<User> = new Schema({
  username: {
    type: String,
    required: [true, "Username is required"],
  },
  email: {
    type: String,
    required: [true, "Email is required"],
    unique: true,
    match: [/.+\@.+\..+/, "Please use a valid email address"],
  },
  password: {
    type: String,
  },
  role: {
    type: String,
    enum: ["user", "admin"],
    default: "user",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});
 
const UserModel =
  mongoose.models.User ||
  mongoose.model<User>("User", UserSchema) as mongoose.Model<User>;
 
export default UserModel;

Mongoose Setup

To connect to the MongoDB database using Mongoose, follow these steps:

  1. Open MongoDB Atlas, create a cluster, and obtain the connection string.
  2. Add the following string in the .env.local file in the root directory of your project:
MONGO_URI=<Paste Your Connection String>

On this page