Connecting

The first thing to implementing a database is to connect to said database whenever you start your bot.

Now, you could also connect to it whenever needed, but it may cause your commands/events to execute slower, due to having to connect each time one is ran.

This tutorial will teach you how to open a database connection when your bot starts, and close it when your bot is turned off.

Types of Databases

Before you implement the code, you need to decide on a database to use for your bot. My recommendation is to use MongoDB, as it is a fast, easy-to-understand database. MongoDB uses a document setup, meaning data is stored on documents in a JSON style, rather than in tables (Like SQL based Databases).

The best database all depends on preferences, but for beginners, MongoDB will be your best option due to its small learning curve. You may also choose an SQL based database, like MariaDB, PostgreSQL, or Redis SQL. Those will not be covered in this tutorial.

MongoDB

Make sure you have the mongoose package installed on your Node.js instance, and then inside of your /source/events/ready/ directory, access yourdatabase-connection.js file.

Inside this file, below requiring the config line, require mongoose from mongoose like this:

const mongoose = require("mongoose");

Now inside this file we will create an "iife" (Immediately Invoked Function Expression). This is a type of function that will be called as soon as it is defined. In simple terms, it will run as soon as the database-connection.js file is registered by Node.js

An "iife" will follow this structure:

(async () => {})();

Inside the curly braces is where our code will go. Now inside the curly braces, we need to add a try-catch block to handle any errors (may we encounter them). Then inside the "try" section of the try-catch block, we can connect to our database, and console log its connection.

(async () => {
  try {
    await mongoose.connect(conf.databaseString);
    console.log("Connected to MongoDB");
  } catch (error) {}
})()

Inside the error block, we can console log the error, should we have any.

Now, when you restart your bot, it should connect to MongoDB.

Last updated