Skip to content

Commit 5add868

Browse files
committed
minor improvements to clarify index creation during save
1 parent 976502c commit 5add868

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

mongoengine/document.py

+12-7
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,7 @@ def _get_collection(cls):
226226
cls._collection = db[collection_name]
227227

228228
# 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.
231230
db = cls._get_db()
232231
if cls._meta.get("auto_create_index", True) and db.client.is_primary:
233232
cls.ensure_indexes()
@@ -411,12 +410,14 @@ def save(
411410
# it might be refreshed by the pre_save_post_validation hook, e.g., for etag generation
412411
doc = self.to_mongo()
413412

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
415420
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()
420421

421422
try:
422423
# Save a new document or update an existing one
@@ -888,6 +889,10 @@ def ensure_indexes(cls):
888889
Document collection (query, save, etc) so unless you disabled `auto_create_index`, you
889890
shouldn't have to call this manually.
890891
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+
891896
.. note:: You can disable automatic index creation by setting
892897
`auto_create_index` to False in the documents meta data
893898
"""

tests/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def _inner(*args, **kwargs):
7171
return func(*args, **kwargs)
7272

7373
pretty_version = ".".join(str(n) for n in mongo_version_req)
74-
pytest.skip(f"Needs MongoDB v{pretty_version}+")
74+
pytest.skip(f"Needs MongoDB {oper.__name__} v{pretty_version}")
7575

7676
_inner.__name__ = func.__name__
7777
_inner.__doc__ = func.__doc__

0 commit comments

Comments
 (0)