MongoDB Connection

On this page we will show you how to connect your mongodb database to the discord bot.

Connection Guide

You can get a MongoDB URL which is used to connect to the database by using this Tutorial:

YOU ONLY NEED THE URL AND NOTHING ELSE!

The connection begins in the load.js file. Here is the code snippet of the connection function:

const mongoose = require('mongoose'); // Import the mongoose module to interact with MongoDB
var mongooseStatus = false
// Define an asynchronous function to establish a MongoDB connection
async function connectToMongoDB() {
    try { // Begin a try block to handle potential errors
        mongoose.set('strictQuery', false); // Disable strict query mode in mongoose

        // Attempt to connect to MongoDB using the URI stored in the environment variable
        mongoose.connect(process.env.MONGOURI, {
            useNewUrlParser: true, // Use the new URL parser to avoid deprecation warnings
            useUnifiedTopology: true // Use the new unified topology layer
        })
        .catch(err => console.error('Could not connect to MongoDB:', err)); // Catch and log any errors during connection

        // Event listener for successfully connecting to the database
        mongoose.connection.on('connected', () => {
            mongooseStatus = true; // Update status to true when the connection is successful
        });
        
        // Event listener for any connection errors
        mongoose.search.connection.on('error', (err) => {
            mongooseStatus = false; // Update status to false if there is an error
        });
        
        // Event listener for disconnection from the database
        mongoose.connection.on('disconnected', () => {
            mongooseStatus = false; // Update status to false when the connection is disconnected
        });
    } catch (error) { // Catch block to handle any errors not related to the connection process
        console.error('Failed to connect to MongoDB:', error); // Log the error message
        process.exit(1); // Terminate the node process with a status code of 1 (indicates failure)
    } 
}
connectToMongoDB();

module.exports = {mongooseStatus}

Last updated