diff --git a/docs/changelog.rst b/docs/changelog.rst index 49371577..fc8b281c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -5,7 +5,8 @@ Changelog Changes in 0.9.X - DEV ====================== -- Generate Unique Indicies for Lists of EmbeddedDocuments #358 +- Ensure Indexes before Each Save #812 +- Generate Unique Indices for Lists of EmbeddedDocuments #358 - Sparse fields #515 - write_concern not in params of Collection#remove #801 - Better BaseDocument equality check when not saved #798 diff --git a/mongoengine/document.py b/mongoengine/document.py index 203b2659..03318c84 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -285,6 +285,8 @@ class Document(BaseDocument): try: collection = self._get_collection() + if self._meta.get('auto_create_index', True): + self.ensure_indexes() if created: if force_insert: object_id = collection.insert(doc, **write_concern) diff --git a/tests/document/indexes.py b/tests/document/indexes.py index 4815350f..d3e37267 100644 --- a/tests/document/indexes.py +++ b/tests/document/indexes.py @@ -18,7 +18,7 @@ __all__ = ("IndexesTest", ) class IndexesTest(unittest.TestCase): def setUp(self): - connect(db='mongoenginetest') + self.connection = connect(db='mongoenginetest') self.db = get_db() class Person(Document): @@ -795,6 +795,33 @@ class IndexesTest(unittest.TestCase): key = indexes["title_text"]["key"] self.assertTrue(('_fts', 'text') in key) + def test_indexes_after_database_drop(self): + """ + Test to ensure that indexes are re-created on a collection even + after the database has been dropped. + + Issue #812 + """ + class BlogPost(Document): + title = StringField() + slug = StringField(unique=True) + + BlogPost.drop_collection() + + # Create Post #1 + post1 = BlogPost(title='test1', slug='test') + post1.save() + + # Drop the Database + self.connection.drop_database(BlogPost._get_db().name) + + # Re-create Post #1 + post1 = BlogPost(title='test1', slug='test') + post1.save() + + # Create Post #2 + post2 = BlogPost(title='test2', slug='test') + self.assertRaises(NotUniqueError, post2.save) if __name__ == '__main__': unittest.main()