Skip to content

Commit 5916227

Browse files
committed
refactor : refacto mongo to to_mongo
1 parent 4a6afb1 commit 5916227

File tree

5 files changed

+37
-10
lines changed

5 files changed

+37
-10
lines changed

fastapi_crudrouter_mongodb/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@
1212
"CRUDLookup",
1313
]
1414

15-
__version__ = "0.0.5"
15+
__version__ = "0.0.7"
1616
__author__ = "Pierre DUVEAU"
1717
__credits__ = ["Pierre DUVEAU", "Adam Watkins"]

fastapi_crudrouter_mongodb/core/models/mongo_model.py

+26
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from bson import ObjectId
22
from pydantic import BaseModel
33

4+
from fastapi_crudrouter_mongodb.core.utils.deprecated_util import deprecated
5+
46

57
class MongoModel(BaseModel):
68

@@ -16,6 +18,7 @@ def from_mongo(cls, data: dict):
1618
mid = data.pop('_id', None)
1719
return cls(**dict(data, id=mid))
1820

21+
@deprecated("use new method 'to_mongo' instead")
1922
def mongo(self, add_id: bool = False, **kwargs):
2023
exclude_none = kwargs.pop('exclude_none', True)
2124
by_alias = kwargs.pop('by_alias', True)
@@ -32,6 +35,29 @@ def mongo(self, add_id: bool = False, **kwargs):
3235
if '_id' not in parsed and 'id' not in parsed and add_id:
3336
parsed['_id'] = ObjectId()
3437
return parsed
38+
39+
def to_mongo(self, add_id: bool = False, exclude_default: bool = False, by_alias: bool = False, **kwargs):
40+
exclude_unset = kwargs.pop('exclude_unset', True)
41+
exclude_default = kwargs.pop('exclude_default', True)
42+
by_alias = kwargs.pop('by_alias', True)
43+
44+
parsed = self.dict(
45+
exclude_unset=exclude_unset,
46+
exclude_defaults=exclude_default,
47+
by_alias=by_alias,
48+
**kwargs,
49+
)
50+
51+
# Mongo uses `_id` as default key. We should stick to that as well.
52+
if '_id' not in parsed and 'id' in parsed:
53+
parsed['_id'] = parsed.pop('id')
54+
if '_id' not in parsed and 'id' not in parsed and add_id:
55+
parsed['_id'] = ObjectId()
56+
return parsed
57+
58+
def convert_to(self, model: BaseModel):
59+
"""Convert the current model into another model. """
60+
return model(**self.dict())
3561

3662
def __init__(self, **pydict):
3763
super().__init__(**pydict)

fastapi_crudrouter_mongodb/core/router/CRUDRouterRepository.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ async def create_one(db, model: MongoModel, collection_name, data: MongoModel):
5555
:return: The created document.
5656
:rtype: dict
5757
"""
58-
response = await db[collection_name].insert_one(data.mongo())
58+
response = await db[collection_name].insert_one(data.to_mongo())
5959
response = await db[collection_name].find_one({"_id": response.inserted_id})
6060
return model.from_mongo(response)
6161

@@ -77,7 +77,7 @@ async def replace_one(db, model: MongoModel, collection_name, id: str, data: Mon
7777
:return: The replaced document.
7878
:rtype: dict
7979
"""
80-
response = await db[collection_name].replace_one({"_id": ObjectId(id)}, data.mongo())
80+
response = await db[collection_name].replace_one({"_id": ObjectId(id)}, data.to_mongo())
8181
response = await db[collection_name].find_one({"_id": response.upserted_id if response.upserted_id is not None else ObjectId(id)})
8282
return model.from_mongo(response)
8383

@@ -99,7 +99,7 @@ async def update_one(db, model: MongoModel, collection_name, id: str, data: Mong
9999
:return: The updated document.
100100
:rtype: dict
101101
"""
102-
response = await db[collection_name].update_one({"_id": ObjectId(id)}, {"$set": data.mongo()})
102+
response = await db[collection_name].update_one({"_id": ObjectId(id)}, {"$set": data.to_mongo()})
103103
response = await db[collection_name].find_one({"_id": response.upserted_id if response.upserted_id is not None else ObjectId(id)})
104104
return model.from_mongo(response)
105105

fastapi_crudrouter_mongodb/core/router/embed/CRUDEmbedRouterRepository.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ async def create_one(db, id: str, parent_collection_name: str, embed_name: str,
6868
"""
6969
Create a new document in the database
7070
"""
71-
document_mongo = data.mongo(add_id=True)
71+
document_mongo = data.to_mongo(add_id=True)
7272
document = await db[parent_collection_name].update_one(
7373
{'_id': ObjectId(id)},
7474
{'$push': {embed_name: document_mongo}}
@@ -81,7 +81,7 @@ async def update_one(db, id: str, embed_id: str, parent_collection_name: str, em
8181
"""
8282
Update a document in the database
8383
"""
84-
document_mongo = data.mongo(add_id=False)
84+
document_mongo = data.to_mongo(add_id=False)
8585
document = await db[parent_collection_name].update_one(
8686
{'_id': ObjectId(id), f'{embed_name}._id': ObjectId(embed_id)},
8787
{'$set': {f'{embed_name}.$': document_mongo}}

fastapi_crudrouter_mongodb/core/router/lookup/CRUDLookupRouterRepository.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from bson import ObjectId
2+
23
from ...models.mongo_model import MongoModel
34

45

@@ -47,7 +48,7 @@ async def get_one(db, collection_name: str, id: str, lookup_id: str, foreign_fie
4748
'path': f'${collection_name}',
4849
'preserveNullAndEmptyArrays': True,
4950
}
50-
},
51+
}
5152
]
5253
)
5354
models = []
@@ -61,23 +62,23 @@ async def create_one(db, collection_name: str, id: str, data, foreign_field: str
6162
Create one document in the database with a lookup
6263
"""
6364
print(data)
64-
response = await db[collection_name].insert_one(data.mongo())
65+
response = await db[collection_name].insert_one(data.to_mongo())
6566
return await get_one(db, collection_name, id, response.inserted_id, foreign_field, local_field, parent_collection_name, parent_model)
6667

6768

6869
async def replace_one(db, collection_name: str, id: str, lookup_id: str, data, foreign_field: str, local_field: str, parent_collection_name: str, parent_model: MongoModel) -> MongoModel:
6970
"""
7071
Update one document in the database with a lookup
7172
"""
72-
response = await db[collection_name].replace_one({"_id": ObjectId(lookup_id)}, data.mongo())
73+
response = await db[collection_name].replace_one({"_id": ObjectId(lookup_id)}, data.to_mongo())
7374
return await get_one(db, collection_name, id, lookup_id, foreign_field, local_field, parent_collection_name, parent_model)
7475

7576

7677
async def update_one(db, collection_name: str, id: str, lookup_id: str, data, foreign_field: str, local_field: str, parent_collection_name: str, parent_model: MongoModel) -> MongoModel:
7778
"""
7879
Update one document in the database with a lookup
7980
"""
80-
response = await db[collection_name].update_one({"_id": ObjectId(lookup_id)}, {"$set": data.mongo()})
81+
response = await db[collection_name].update_one({"_id": ObjectId(lookup_id)}, {"$set": data.to_mongo()})
8182
return await get_one(db, collection_name, id, lookup_id, foreign_field, local_field, parent_collection_name, parent_model)
8283

8384

0 commit comments

Comments
 (0)