LogicGoInfotechSpaces commited on
Commit
ca6fc55
·
1 Parent(s): 41f748f

Fix MongoDB database selection - use database from connection string

Browse files

- Extract database name from MONGO_URI connection string if present
- Fallback to 'object_remover' only if no database in connection string
- Add detailed logging showing which database is being used
- This ensures logs are stored in the correct database specified in MONGO_URI

Files changed (1) hide show
  1. api/main.py +15 -3
api/main.py CHANGED
@@ -73,12 +73,24 @@ grid_fs = None
73
  if MONGO_URI:
74
  try:
75
  mongo_client = MongoClient(MONGO_URI)
76
- mongo_db = mongo_client["object_remover"]
 
 
 
 
 
 
 
 
 
 
 
 
77
  mongo_logs = mongo_db["api_logs"]
78
  grid_fs = GridFS(mongo_db)
79
- log.info("MongoDB connection initialized successfully")
80
  except Exception as err:
81
- log.error("Failed to initialize MongoDB connection: %s", err)
82
  log.warning("GridFS operations will be disabled. Set MONGO_URI or MONGODB_URI environment variable.")
83
  else:
84
  log.warning("MONGO_URI not set. GridFS operations will be disabled. Upload endpoints will not work.")
 
73
  if MONGO_URI:
74
  try:
75
  mongo_client = MongoClient(MONGO_URI)
76
+ # Try to get database from connection string first
77
+ try:
78
+ mongo_db = mongo_client.get_default_database()
79
+ log.info("Using database from connection string: %s", mongo_db.name)
80
+ except Exception as db_err:
81
+ mongo_db = None
82
+ log.warning("Could not extract database from connection string: %s", db_err)
83
+
84
+ # Fallback to 'object_remover' if no database in connection string
85
+ if mongo_db is None:
86
+ mongo_db = mongo_client["object_remover"]
87
+ log.info("Using default database: object_remover")
88
+
89
  mongo_logs = mongo_db["api_logs"]
90
  grid_fs = GridFS(mongo_db)
91
+ log.info("MongoDB connection initialized successfully - Database: %s, Collection: %s", mongo_db.name, mongo_logs.name)
92
  except Exception as err:
93
+ log.error("Failed to initialize MongoDB connection: %s", err, exc_info=True)
94
  log.warning("GridFS operations will be disabled. Set MONGO_URI or MONGODB_URI environment variable.")
95
  else:
96
  log.warning("MONGO_URI not set. GridFS operations will be disabled. Upload endpoints will not work.")