Reputation: 3459
If I have a document like:
class Page(Document):
title = StringField(max_length=200, required=True)
date_modified = DateTimeField(default=datetime.datetime.now)
and I want to update it to:
class Page(Document):
page_title = StringField(max_length=200, required=True)
date_modified = DateTimeField(default=datetime.datetime.now)
what is the best way to handle the database migration in mongoengine? I would imagine you could iterate through the database and pull the objects that have that field and add them back in with the new field then drop all objects that have that field, but it'd be nice if there was an idiomatic way to handle this sort of thing.
Upvotes: 4
Views: 979
Reputation: 7630
I think the easiest way to do it would be by a two-step change of the class. First add the new field and remove the "required" constraint:
class Page(Document):
title = StringField(max_length=200)
page_title = String(max_length=200)
date_modified = DateTimeField(default=datetime.datetime.now)
Then run the following commands:
for page in Page.objects():
page.page_title = page.title
page.save()
Page.objects.update(unset__title=1) ## Unset the title field of the documents
That will update the documents of your DB without having to drop them (which is useful because they will keep the same id).
Then you make the final modification to your class, as you wanted:
class Page(Document):
page_title = StringField(max_length=200, required=True)
date_modified = DateTimeField(default=datetime.datetime.now)
Upvotes: 5