@@ -226,8 +226,7 @@ def _get_collection(cls):
226
226
cls ._collection = db [collection_name ]
227
227
228
228
# Ensure indexes on the collection unless auto_create_index was
229
- # set to False.
230
- # Also there is no need to ensure indexes on slave.
229
+ # set to False. Plus, there is no need to ensure indexes on slave.
231
230
db = cls ._get_db ()
232
231
if cls ._meta .get ("auto_create_index" , True ) and db .client .is_primary :
233
232
cls .ensure_indexes ()
@@ -411,12 +410,14 @@ def save(
411
410
# it might be refreshed by the pre_save_post_validation hook, e.g., for etag generation
412
411
doc = self .to_mongo ()
413
412
414
- if self ._meta .get ("auto_create_index_on_save" , False ):
413
+ # Initialize the Document underlying pymongo.Collection (+create indexes) if not already initialized
414
+ # Important to do this here to avoid that the index creation gets wrapped in the try/except block below
415
+ # and turned into mongoengine.OperationError
416
+ if self ._collection is None :
417
+ _ = self ._get_collection ()
418
+ elif self ._meta .get ("auto_create_index_on_save" , False ):
419
+ # ensure_indexes is called as part of _get_collection so no need to re-call it again here
415
420
self .ensure_indexes ()
416
- else :
417
- # Call _get_collection so that errors from ensure_indexes are not
418
- # wrapped in OperationError, see test_primary_key_unique_not_working.
419
- self ._get_collection ()
420
421
421
422
try :
422
423
# Save a new document or update an existing one
@@ -888,6 +889,10 @@ def ensure_indexes(cls):
888
889
Document collection (query, save, etc) so unless you disabled `auto_create_index`, you
889
890
shouldn't have to call this manually.
890
891
892
+ This also gets called upon every call to Document.save if `auto_create_index_on_save` is set to True
893
+
894
+ If called multiple times, MongoDB will not re-recreate indexes if they exist already
895
+
891
896
.. note:: You can disable automatic index creation by setting
892
897
`auto_create_index` to False in the documents meta data
893
898
"""
0 commit comments