| # config/db.py | |
| from pymongo import MongoClient | |
| import os | |
| from dotenv import load_dotenv | |
| # Load environment variables from a .env file | |
| load_dotenv() | |
| # MongoDB URI and Database name (retrieved from environment variables) | |
| MONGO_URI = os.getenv("MONGO_URI", "mongodb://localhost:27017") # Fallback to local MongoDB if not set | |
| DB_NAME = os.getenv("DB_NAME", "poultry_farm") # Fallback database name if not set | |
| # Initialize MongoDB client | |
| client = MongoClient(MONGO_URI) | |
| # Access the database | |
| db = client[DB_NAME] | |
| # Collections (define and expose MongoDB collections to be used in the system) | |
| users_collection = db.users # User collection | |
| logs_collection = db.logs # Logs collection (e.g., health logs, usage logs) | |
| inventory_collection = db.inventory # Inventory collection for feed, medicines, etc. | |
| health_collection = db.health # Health collection for poultry health records | |
| usage_collection = db.usage # Assistant usage tracking collection | |
| # Test the database connection | |
| try: | |
| # Print a list of databases to ensure connection is successful | |
| print("Databases in MongoDB:", client.list_database_names()) | |
| print(f"Connected to MongoDB database: {DB_NAME}") | |
| except Exception as e: | |
| print(f"Error connecting to MongoDB: {e}") | |