Skip to content

Commit

Permalink
fix!: Uses upsert in save method
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Saving entities will upsert if the id is present
  • Loading branch information
jefersondaniel committed Sep 13, 2023
1 parent 561c122 commit 1a89b5b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic_mongo/abstract_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def save(self, model: T) -> Union[InsertOneResult, UpdateResult]:
if model.id:
mongo_id = document.pop("_id")
return self.get_collection().update_one(
{"_id": mongo_id}, {"$set": document}
{"_id": mongo_id}, {"$set": document}, upsert=True
)

result = self.get_collection().insert_one(document)
Expand Down
15 changes: 15 additions & 0 deletions test/test_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ def test_save(self, database):
"bars": [{"apple": "x", "banana": "y"}],
} == database["spams"].find()[0]

def test_save_upsert(self, database):
spam_repository = SpamRepository(database=database)
spam = Spam(
id=ObjectId("65012da68ea5a4798502f710"),
foo=Foo(count=1, size=1.0),
bars=[]
)
spam_repository.save(spam)

assert {
"_id": ObjectId(spam.id),
"foo": {"count": 1, "size": 1.0},
"bars": [],
} == database["spams"].find()[0]

def test_delete(self, database):
spam_repository = SpamRepository(database=database)
foo = Foo(count=1, size=1.0)
Expand Down

0 comments on commit 1a89b5b

Please sign in to comment.