Migrations for MongoEngine
A MongoDB collection does not have a strict schema, the documents in one collection can have different fields. But in MongoEngine the schema is provided on an application level and there is a validation. So if you’ll remove a field from the Document
and it’s still exists in the database, there will be a mongoengine.errors.FieldDoesNotExist
exception. If there is no need in the schema validation, a dynamic schema can be used.
So when there is a strict schema, it’s good to have a tool to make an updates for the documents in the collection when something changes.
For SQL databases some apps exist to solve it, like Alembic or Django Migrations. I created a similar app Flask MongoEngine Migrations based on the idea from Django Data Migrations
An example of use
The app should be initialized with FlaskMigrations(app)
, then an empty migration can be created with
flask migration_create name_of_migration_with_underscores
It will create a migration file 0001_name_of_migration_with_underscores.py
in the migrations
folder. You will need to modify it:
def up(db):
db['client'].update_many({}, {'$unset': {'some_field': ''}})
def down(db):
db['client'].update_many({}, {'$set': {'some_field': ''}})
After that it can be used with flask migration_up
and flask migration_down 0001
commands.