I am trying to make a Discord bot and have a Mongodb to store all the user data. I have never set up a db before but I think i have it all setup correctly and built with docker-compose.
For some reason I cannot seem to connect to the db using my code or using Compass (Mongodb gui).
Here is how I build it with docker-compose:
services:
bot:
build: .
depends_on:
- db
ports:
- "8080:80"
db:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
volumes:
- admin_bot_db:/data/db
ports:
- "28017:28017"
volumes:
admin_bot_db:```
Here is my .env file:
```BOT_TOKEN=your_discord_token
MONGODB=mongodb://root:root@db:28017/bot_db #change this if you use a different URI
ADMIN_ROLE=your_role_id
USER_ROLE=your_role_id
BOT_CHANNEL=your_channel_id
ADMIN_CHANNEL=your_channel_id```
This is my code:
```import os
import discord
from discord.ext import commands
from pymongo import MongoClient
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
async def load_db():
try:
# Connect to your MongoDB
mongodb = os.getenv('MONGODB')
print(f"Connecting to MongoDB at {mongodb}")
client = MongoClient(mongodb)
db = client.admin_bot_db
return db
except Exception as e:
print(f"Error connecting to MongoDB: {e}")
return None```