fix: make close() sync (motor close is sync); guard doc[key] on missing fields

close() was async but only called motor's synchronous client.close(), misleading callers into awaiting it; it is now a plain def and the docstring + README examples drop the await. get_document_hashmap/get_document_fields indexed doc[key] unguarded, so a doc missing the field raised KeyError that the broad except swallowed, conflating 'no documents' with 'field absent'; both now skip docs lacking the key.

Signed-off-by: disqualifier <dev@disqualifier.me>
This commit is contained in:
disqualifier 2026-06-28 17:46:20 -04:00
parent 6a9de93691
commit eabfe0cbc3
2 changed files with 6 additions and 6 deletions

View File

@ -28,7 +28,7 @@ from mongo import Mongo
db = Mongo(conn_string, database) # attach as bot.db / app.db
users = await db.get_documents("users", {"active": True})
await db.close() # on shutdown
db.close() # on shutdown (sync)
```
**Module proxy (back-compat)** — arm once, then call bare:

View File

@ -5,7 +5,7 @@ object (preferred), one client per process:
from mongo import Mongo
bot.db = Mongo(conn_string, database)
await bot.db.get_documents("users", {"active": True})
await bot.db.close() # on shutdown
bot.db.close() # on shutdown (sync)
module proxy (back-compat), arm once then call bare:
import mongo # not `from mongo import ...`
@ -61,8 +61,8 @@ class Mongo:
log.exception("db.ping()")
return False
async def close(self) -> None:
"""close the client pool on shutdown"""
def close(self) -> None:
"""close the client pool on shutdown (sync — motor's close() is synchronous)"""
self._client.close()
# -------------------------------------------------------------------------
@ -184,7 +184,7 @@ class Mongo:
"""return matching documents keyed into a dict by the given field"""
try:
cursor = self._db[collection].find(target)
return {doc[key]: doc async for doc in cursor}
return {doc[key]: doc async for doc in cursor if key in doc}
except Exception:
log.exception(f"db.get_document_hashmap() on {collection}")
return {}
@ -195,7 +195,7 @@ class Mongo:
"""return a flat list of one field's value across matching documents"""
try:
cursor = self._db[collection].find(target, fields)
return [doc[key] async for doc in cursor]
return [doc[key] async for doc in cursor if key in doc]
except Exception:
log.exception(f"db.get_document_fields() on {collection}")
return []