Home > database >  Connect discord bot to mongo DB with event handler
Connect discord bot to mongo DB with event handler

Time:05-02

I am building a discord bot, and I'm trying to connect it to a mongo DB.

The way my code is structured, I have a 'main' file, called index.js, where I run my main code, on the main code, I handle the events. Inside the event 'on ready'(which is executed once) I connect to the DB. This is how I handle the events on index.js:

for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
    client.once(event.name, (...args) => event.execute(...args, commands));
} else {
    client.on(event.name, (...args) => event.execute(...args, commands));
}

}

To connect to the DB, I have an event script, called ready, that is called only once. The problem I'm having is, when I try to connect to the DB, I get stuck without a response. I'm using mongoose js and following their documentation to connect. Their documentation states that I need to use an async function to connect.

When I do that, the code gets 'stuck'. If I remove the async and await statement form the code below, it works. It would be ok to use it like that, but that's not a good pratice. Code fore ready.js follows:

const mongoose = require('mongoose')
require('dotenv').config()
const testSchema = require('../test-schema')

module.exports = {
    name: 'ready',
    once: true,



    async execute(client, commands) {
        console.log(`Ready! Logged in as ${client.user.tag}`);

        await mongoose.connect(process.env.MONGO_URI);
        console.log("Database Connected!");

    },
};

So, is it ok to just remove the async and await?

Thanks in advance.

Disclaimer: English is not my first language, sorry if it sounds confuse.

CodePudding user response:

So, I figured it out (sort of).

Changed my code to the following, and it worked:

const mongoose = require('mongoose')
require('dotenv').config()


module.exports = {
    name: 'ready',
    once: true,

    async execute(client, commands) {
        console.log(`Ready! Logged in as ${client.user.tag}`);

        main().catch(err => console.log(err));

        console.log("Database Connected!");

    },
};


async function main() {
    await mongoose.connect(process.env.MONGO_URI);
}

Basically, put the connection inside the main function, and called it on the execute method.

It worked.

  • Related