Cannot read properties of undefined (reading db)

using ver 6.3 of the mongodb package on node.js I get the error mentioned in the title when trying to access my database. I’ve gone through the docs and my code matches the example provided in the quickstart. So I don’t know why this issue could be occuring.

code for connecting:

async function connectToDatabase() {
    try {
        dbClient = new MongoClient(mongoURI);
        console.log('Connected to MongoDB');
    } catch (error) {
        console.error('Error connecting to MongoDB:', error);
    };
};

where the error occurs/where i call the database:

async function processEvent(event, dbClient) {
    try {
        const database = dbClient.db('BotServices');
        const eventsCollection = database.collection('eventData');

        const currentTime = new Date();
        const eventTime = new Date(event.scheduledStartAt);

        const eventData = {
            id: event.id,
            name: event.name,
            startTime: event.scheduledStartAt,
            endTime: event.scheduledEndAt,
            server: event.guild.id,
            // Add more fields as needed
        };

Looks like this line is falling over as dbClient is not set, are you sure that the call to connectToDatabase has taken place first and that it has completed before the second call is made?

@Iris_N_A

const database = dbClient.db('BotServices');
        const eventsCollection = database.collection('eventData');

The error could be because of the case when you try to access the database before connecting.
Ensure you use ‘await’ for synchronous operations to prevent potential errors, especially when accessing the database before connecting:

const database = await dbClient.db('BotServices');
 const eventsCollection = await database.collection('eventData');