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?