Features
Database

Database Setup with MongoDB

The boilerplate project includes MongoDB pre-installed, enabling you to quickly add a database to your projects. Follow these steps to set up and use MongoDB in your application.

Getting Started

Step 1: Add Your MongoDB URI

First, set up your MongoDB connection string by adding it to your environment variables:

MONGODB_URI=your-mongodb-connection-string

Step 2: Create a New Model

Define a new model using Mongoose. Here is an example of creating a Post model.

import mongoose, { Schema, Document } from "mongoose";
 
export interface IPost extends Document {
  userId: mongoose.Schema.Types.ObjectId;
  text: string;
  image?: string;
  likes?: number;
}
 
const PostSchema: Schema = new Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "users",
      required: true,
    },
    text: { type: String, required: true },
    image: { type: String },
    likes: { type: Number, default: 0 },
  },
  {
    timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
  }
);
 
export const Post =
  mongoose.models.posts || mongoose.model<IPost>("posts", PostSchema);

Step 3: Add a New Entry to the Model

You can now add a new entry to the Post model in your database.

const newPost = new Post({
  userId,
  text,
  image,
});
 
return await newPost.save();

Step 4: Query Your Database

You can also query your database to retrieve entries for the model.

const posts = await Post.find({ userId });

Summary

By following these steps, you can easily set up and use MongoDB in your project. Define your models, add entries, and perform queries to interact with your database effectively.