如何使用Meteor进行数据库迁移? 在Ruby on Rails中有ActiveRecord :: Migration。 Meteor中是否有类似的机制?
例如,我创建了一个带有某些用户数据的应用程序。我使用JSON格式将数据存储在Mongo中。 应用程序发生更改,需要更改JSON数据库架构。 我可以编写一个迁移方法来更改架构,但是仅当服务器数据库过时时才希望运行此方法。
这方面没有内置的功能。我目前自己做的方式类似于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"});
}
});
如果你想支持向下迁移(查找指定迁移的存在并将其反转)、对迁移进行排序以及将每个迁移拆分为单独的文件,你可以扩展此技术。
想象一下自动化这个过程的智能包,会很有趣。
正如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}
});