Discord bot throwing MongoDB connection error on startup

I’m building a Discord bot for moderation commands and getting a TypeError when trying to start it. The error says Cannot read properties of undefined (reading 'startsWith') and it’s coming from the MongoDB connection string validation.

require('dotenv').config()
const { Client, Collection, GatewayIntentBits } = require('discord.js')
const { MongoClient } = require('mongodb')

// Database setup
const connectionString = process.env.DB_CONNECTION_STRING
const dbClient = new MongoClient(connectionString, { useNewUrlParser: true, useUnifiedTopology: true })

// Handle server join events
bot.on('guildCreate', async (server) => {
  console.log(`Joined server: ${server.name}`)
  
  try {
    await dbClient.connect()
    const db = dbClient.db('discord_bot')
    const servers = db.collection('server_list')
    
    await servers.insertOne({ serverId: server.id, serverName: server.name })
  } catch (err) {
    console.error('Database error:', err)
  } finally {
    await dbClient.close()
  }
})

// Handle server leave events  
bot.on('guildDelete', async (server) => {
  console.log(`Left server: ${server.name}`)
  
  try {
    await dbClient.connect()
    const db = dbClient.db('discord_bot')
    const servers = db.collection('server_list')
    
    await servers.deleteOne({ serverId: server.id })
  } catch (err) {
    console.error('Database removal error:', err)
  } finally {
    await dbClient.close()
  }
})

I think the issue is that my environment variable isn’t loading properly even though the .env file is in the same directory as my main script. Has anyone faced this MongoDB connection string issue before?

Double-check your .env file isn’t actually named .env.txt - Windows hides file extensions by default. Also, move dotenv.config() to the very top of your file before any other requires. I had the same problem when modules tried accessing env vars before dotenv loaded them.

Had the exact same error last month. My .env file wasn’t being read because I had a typo in the variable name. Check that your .env file actually has DB_CONNECTION_STRING and not MONGODB_CONNECTION_STRING or DATABASE_URL. Also caught me off guard - make sure your .env file is saved as UTF-8 without BOM. I’d add some basic validation after loading the environment variables: if (!connectionString) { throw new Error('DB_CONNECTION_STRING is required') } before creating the MongoClient. You’ll get a clearer error message if the variable isn’t loading properly instead of that cryptic startsWith error.

This error usually happens when your environment variable is undefined, so MongoDB gets undefined instead of your actual connection string. First, check your .env file for extra spaces around the equals sign - it should look like DB_CONNECTION_STRING=mongodb://... with no spaces. Make sure you’re using the same variable name everywhere. You can test if it’s loading correctly by adding console.log(process.env.DB_CONNECTION_STRING) right after your dotenv config. Also, I noticed you’re connecting and disconnecting from MongoDB on every guild event - that’s really inefficient. You should connect once at startup and reuse that connection for all events. All that connecting/disconnecting might be causing your issues too.