import motor.motor_asyncio import os import logging from dotenv import load_dotenv load_dotenv() logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) MONGO_URI = os.getenv("MONGO_URI") if not MONGO_URI: raise ValueError("MONGO_URI is not set") logger.info("Connecting to MongoDB") client = None db = None users_collection = None async def get_database(): global client, db, users_collection if client is None: try: logger.info("Connecting to MongoDB") client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI) db = client["fastapi_db"] users_collection = db["users"] logger.info("Successfully connected to MongoDB") except Exception as e: logger.error(f"MongoDB connection failed: {e}") raise return db async def get_users_collection(): await get_database() return users_collection async def close_database(): global client if client: logger.info("Closing MongoDB connection") client.close() client = None