From eabfe0cbc3edbc347038384edcf7477a3ca97bfc Mon Sep 17 00:00:00 2001 From: disqualifier Date: Sun, 28 Jun 2026 17:46:20 -0400 Subject: [PATCH] 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 --- README.md | 2 +- src/mongo/mongo.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 63b9bf9..f9280f5 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/src/mongo/mongo.py b/src/mongo/mongo.py index 24baeba..212aa7b 100644 --- a/src/mongo/mongo.py +++ b/src/mongo/mongo.py @@ -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 []