Refactor MongoDB handling for cleaner and safer code.
Browse filesReplaced deprecated `default` with `default_factory` for ObjectId to ensure proper instantiation. Simplified message insertion by directly calling `to_mongo()` inline, reducing temporary variable usage.
- cbh/api/message/db_requests.py +1 -2
- cbh/core/database.py +1 -2
cbh/api/message/db_requests.py
CHANGED
|
@@ -26,6 +26,5 @@ async def create_message_obj(chat_id: str, message: CreateMessageRequest) -> Mes
|
|
| 26 |
author=message.author,
|
| 27 |
text=message.text,
|
| 28 |
moduleResponse=message.moduleResponse)
|
| 29 |
-
|
| 30 |
-
await settings.DB_CLIENT.messages.insert_one(t)
|
| 31 |
return message
|
|
|
|
| 26 |
author=message.author,
|
| 27 |
text=message.text,
|
| 28 |
moduleResponse=message.moduleResponse)
|
| 29 |
+
await settings.DB_CLIENT.messages.insert_one(message.to_mongo())
|
|
|
|
| 30 |
return message
|
cbh/core/database.py
CHANGED
|
@@ -7,13 +7,12 @@ from bson import ObjectId
|
|
| 7 |
PyObjectId = Annotated[str, BeforeValidator(str)]
|
| 8 |
|
| 9 |
class MongoBaseModel(BaseModel):
|
| 10 |
-
id: Optional[PyObjectId] = Field(alias="_id",
|
| 11 |
|
| 12 |
model_config = ConfigDict(
|
| 13 |
populate_by_name=True,
|
| 14 |
arbitrary_types_allowed=True,
|
| 15 |
json_encoders={PyObjectId: str},
|
| 16 |
-
response_by_alias=False
|
| 17 |
)
|
| 18 |
|
| 19 |
def to_mongo(self):
|
|
|
|
| 7 |
PyObjectId = Annotated[str, BeforeValidator(str)]
|
| 8 |
|
| 9 |
class MongoBaseModel(BaseModel):
|
| 10 |
+
id: Optional[PyObjectId] = Field(alias="_id", default_factory=ObjectId)
|
| 11 |
|
| 12 |
model_config = ConfigDict(
|
| 13 |
populate_by_name=True,
|
| 14 |
arbitrary_types_allowed=True,
|
| 15 |
json_encoders={PyObjectId: str},
|
|
|
|
| 16 |
)
|
| 17 |
|
| 18 |
def to_mongo(self):
|