38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
import logging
|
|
import uuid
|
|
from typing import Optional, List, Dict
|
|
|
|
from motor.motor_asyncio import AsyncIOMotorDatabase
|
|
|
|
from app.repositories.abc import IDocumentStore
|
|
|
|
|
|
class MongoDB(IDocumentStore):
|
|
|
|
def __init__(self, mongo_db: AsyncIOMotorDatabase):
|
|
self._mongo_db = mongo_db
|
|
self._logger = logging.getLogger(__name__)
|
|
|
|
async def save_to_db(self, collection: str, item, doc_id: Optional[str] = None) -> Optional[str]:
|
|
collection_ref = self._mongo_db[collection]
|
|
|
|
if doc_id is None:
|
|
doc_id = str(uuid.uuid4())
|
|
|
|
item['id'] = doc_id
|
|
|
|
result = await collection_ref.insert_one(item)
|
|
if result.inserted_id:
|
|
# returning id instead of _id
|
|
self._logger.info(f"Document added with ID: {doc_id}")
|
|
return doc_id
|
|
|
|
return None
|
|
|
|
async def get_all(self, collection: str) -> List[Dict]:
|
|
cursor = self._mongo_db[collection].find()
|
|
return [document async for document in cursor]
|
|
|
|
async def get_doc_by_id(self, collection: str, doc_id: str) -> Optional[Dict]:
|
|
return await self._mongo_db[collection].find_one({"id": doc_id})
|