Meteor如何执行数据库迁移?

25

如何使用Meteor进行数据库迁移? 在Ruby on Rails中有ActiveRecord :: Migration。 Meteor中是否有类似的机制?

例如,我创建了一个带有某些用户数据的应用程序。我使用JSON格式将数据存储在Mongo中。 应用程序发生更改,需要更改JSON数据库架构。 我可以编写一个迁移方法来更改架构,但是仅当服务器数据库过时时才希望运行此方法。

3个回答

36

这方面没有内置的功能。我目前自己做的方式类似于Rails,但是作为启动的一部分而不是单独的任务。首先创建一个名为Migrations的Meteor.Collection,然后对于每个离散的迁移,在server子目录下创建一个在启动时运行的函数。它应该仅在之前未运行过迁移的情况下运行迁移,并且在完成后应该将迁移标记为Migrations集合中的已完成。

// 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"});
  }
});

如果你想支持向下迁移(查找指定迁移的存在并将其反转)、对迁移进行排序以及将每个迁移拆分为单独的文件,你可以扩展此技术。

想象一下自动化这个过程的智能包,会很有趣。


我可能最终会有动力使用这个逻辑制作一个智能包。这仍然比晦涩的Meteor方法要好。 - wizonesolutions
如果您在同一数据库上运行多个服务器(多个Web服务器或微服务),当5个服务器都运行相同的查询时,您可能会遇到麻烦。该软件包似乎使用了锁定机制 - Michael Cole

6

正如Aram在评论中所指出的那样,percolate:migrations包可以提供您所需的内容。示例

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}
});

5

5
还有一个名为https://github.com/percolatestudio/meteor-migrations的项目,我认为它的设计比https://github.com/rantav/meteor-migrations更清晰。 - Aram Kocharyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接