Meteor how to perform database migrations?

点点圈 提交于 2019-12-31 08:29:09

问题


How do you perform database migrations with Meteor? With Ruby on Rails there is ActiveRecord::Migration. Is there an equivalent mechanism in Meteor?

For example, I make an app with some user data. I'm storing the data in Mongo using a JSON format. The app changes, and the JSON database schema needs to change. I can write a migration method to change the schema, however, I only want this to run if the server database is out of date.


回答1:


There's nothing built in for this. What I've done myself for now is similar to how Rails works, but as part of startup instead of a separate task. First create a Meteor.Collection called Migrations, and then for each discrete migration, create a function under the server subdirectory that runs on startup. It should only run the migration if it hasn't run before, and it should flag the migration in the Migrations collection once its done.

// database migrations
Migrations = new Meteor.Collection('migrations');

Meteor.startup(function () {
  if (!Migrations.findOne({name: "addFullName"})) {
    Users.find().forEach(function (user) {
      Users.update(user._id, {$set: {fullname: users.firstname + ' ' + users.lastname}});
    });
    Migrations.insert({name: "addFullName"});
  }
});

You could extend this technique to support down migrations (look for the existence of a given migration and reverse it), enforce a sort order on the migrations, and split each migration into a separate file if you wanted.

It'd be interesting to think about a smart package for automating this.




回答2:


As Aram pointed already in the comment, percolate:migrations package gives you what you need. Sample

Migrations.add({
    version: 1,
    name: 'Adds pants to some people in the db.',
    up: function() {//code to migrate up to version 1}
    down: function() {//code to migrate down to version 0}
});

Migrations.add({
    version: 2,
    name: 'Adds a hat to all people in the db who are wearing pants.',
    up: function() {//code to migrate up to version 2}
    down: function() {//code to migrate down to version 1}
});



回答3:


I created a smart package for this use case.
See https://atmosphere.meteor.com/package/migrations



来源:https://stackoverflow.com/questions/10365496/meteor-how-to-perform-database-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!