|
12 | 12 | TopLevelDocumentMetaclass, get_document) |
13 | 13 | from mongoengine.common import _import_class |
14 | 14 | from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db |
15 | | -from mongoengine.context_managers import switch_collection, switch_db |
| 15 | +from mongoengine.context_managers import (set_write_concern, |
| 16 | + switch_collection, |
| 17 | + switch_db) |
16 | 18 | from mongoengine.errors import (InvalidDocumentError, InvalidQueryError, |
17 | 19 | SaveConditionError) |
18 | 20 | from mongoengine.python_support import IS_PYMONGO_3 |
@@ -426,11 +428,18 @@ def _save_create(self, doc, force_insert, write_concern): |
426 | 428 | Helper method, should only be used inside save(). |
427 | 429 | """ |
428 | 430 | collection = self._get_collection() |
429 | | - |
430 | | - if force_insert: |
431 | | - return collection.insert(doc, **write_concern) |
432 | | - |
433 | | - object_id = collection.save(doc, **write_concern) |
| 431 | + with set_write_concern(collection, write_concern) as wc_collection: |
| 432 | + if force_insert: |
| 433 | + return wc_collection.insert_one(doc).inserted_id |
| 434 | + # insert_one will provoke UniqueError alongside save does not |
| 435 | + # therefore, it need to catch and call replace_one. |
| 436 | + if '_id' in doc: |
| 437 | + raw_object = wc_collection.find_one_and_replace( |
| 438 | + {'_id': doc['_id']}, doc) |
| 439 | + if raw_object: |
| 440 | + return doc['_id'] |
| 441 | + |
| 442 | + object_id = wc_collection.insert_one(doc).inserted_id |
434 | 443 |
|
435 | 444 | # In PyMongo 3.0, the save() call calls internally the _update() call |
436 | 445 | # but they forget to return the _id value passed back, therefore getting it back here |
|
0 commit comments