logo

Constatic

Discord Bot BasePresetsDatabasesMongoDB

MongoDB

See how to use the mongodb database preset

You will need to have a MongoDB database to use this preset! If you want to create one in the cloud for free, follow this guide

Env

The environment variable validation scheme receives a new property, now it is necessary to define the URI of your database in the MONGO_URI variable:

.env
# ...
MONGO_URI=uri
# ... 

Here's an example of the format of a MongoDB database URI:

  • mongodb+srv://<user>:<password>@<database>.subdomain.mongodb.net

Estrutura

The structure of this template was made using the mongoose library, so to create our data we used mongoose schemas

The index.ts file in the src/database folder must connect to the database:

src/database/index.ts
import mongoose, { InferSchemaType, model } from "mongoose";
import { guildSchema } from "./schemas/guild.js";
import { memberSchema } from "./schemas/member.js";
import { logger } from "#settings";
import chalk from "chalk";
 
try {
   await mongoose.connect(process.env.MONGO_URI, { dbName: "database" });
   logger.success(chalk.green("MongoDB connected"));
} catch(err){
   logger.error(err);
   process.exit(1);
}
 
export const db = {
   guilds: model("guild", guildSchema, "guilds"),
   members: model("member", memberSchema, "members")
};
 
export type GuildSchema = InferSchemaType<typeof guildSchema>;
export type MemberSchema = InferSchemaType<typeof memberSchema>;

The document models are stored in the db variable object, that is, for each new document schema that you create, place the model as a property of this variable

So when you need to create, read, update or delete data, simply import the db variable from #database and use the model methods:

src/discord/commands/members.ts
import { createCommand } from "#base";
import { db } from "#database"; 
import { ApplicationCommandType } from "discord.js";
 
createCommand({
    name: "members",
    description: "Consultar os documentos de todos os membros",
    type: ApplicationCommandType.ChatInput,
    async run(interaction){
        const documents = await db.members.find(); 
 
        for(const doc of documents){
            console.log(doc.id);
            console.log(doc.guildId);
        }
 
        // ...
    }
});

Always use the db variable from the "#database" import shortcut, this way the file containing the code that makes the connection to the database is called.

Schemas

Create your mongoose schemas in the src/database/schemas/ folder for better organization. See the example schemas that come by default:

src/database/schemas/member.ts
import { Schema } from "mongoose";
import { t } from "../utils.js";
 
export const memberSchema = new Schema(
    {
        id: t.string,
        guildId: t.string,
        wallet: {
            coins: { type: Number, default: 0 },
        }
    },
    {
        statics: {
            async get(member: { id: string, guild: { id: string } }) {
                const query = { id: member.id, guildId: member.guild.id };
                return await this.findOne(query) ?? this.create(query);
            }
        }
    },
);

After creating your schema, import it into the index.ts file in the src/database folder and create a model for it in the db variable object:

src/database/index.ts

import /* ... */ { /* ... */ model } from "mongoose";
import { guildSchema } from "./schemas/guild.js";
import { memberSchema } from "./schemas/member.js";
 
// ...
 
export const db = {
    guilds: model("guild", guildSchema, "guilds"), 
    members: model("member", memberSchema, "members") 
};
 
// ...

If you need the types of the document properties, extract the type from the schemas:

src/database/index.ts

import /* ... */ { /* ... */ InferSchemaType } from "mongoose";
import { guildSchema } from "./schemas/guild.js";
import { memberSchema } from "./schemas/member.js";
 
// ...
 
export type GuildSchema = InferSchemaType<typeof guildSchema>;
export type MemberSchema = InferSchemaType<typeof memberSchema>;

On this page