mongoose迁徙
任何人有一个迁移模块,他们使用mongoose插件迁移mongodb数据?
我目前正在使用“迁移”模块,除了事实上我需要在每个向上/向下创build/销毁我的连接。
IE
// Setup mongoose var mongoose = require('mongoose') , Role = require('../models/role') , User = require('../models/user'); exports.up = function(next) { // get a brand new connection for this patch. mongoose.connect('mongodb://localhost/sagedb'); var adminUser = { username: 'admin', password: 'admin' }; User.createUser(adminUser, function(err, user) { if (err) { mongoose.disconnect(); // Make sure to close connection return next(err); } mongoose.disconnect(next); // Make sure to close connection }); }; exports.down = function(next) { mongoose.connect('mongodb://localhost/sagedb'); // new connection for down User.getUserByUsername('admin', function(err, user) { if (err) { mongoose.disconnect(function() { // make sure to close connection return next(err); }); } if (!user) { mongoose.disconnect(); // make sure to close connection return next(); } User.deleteUser(user, function(err, user) { console.log('deleted user'); mongoose.disconnect(next); // make sure to close connection }); }); };
可能是一个更好的方法来做到这一点。 想知道如果唯一的select是创build我自己的模块来启动连接一次,并在所有补丁完成时closures它。
我已经看到了在数据库收集中跟踪迁移的mongoose迁移。 没有真正具体的mongoose恕我直言,我宁愿仍然使用.migrate文件,但只有打开连接一次。
这个问题的原因是,你每次连接“连接”,每一次迁移这就是为什么你必须断开连接。 如果用mongoose.createConnectionreplace连接,情况也是如此。 你将需要closures它。
怎么解决?
移动
var mongoose = require('mongoose') , Role = require('../models/role') , User = require('../models/user');
进入像db这样的模块
var mongoose = require('mongoose') , Role = require('../models/role') , User = require('../models/user'); module.exports = mongoose
只需要它
var mongoose = require('./db')
所以你会有:
- 单一连接
- 所有模型加载在一个地方
- 清理迁移中的代码
您也可以尝试我的migrate-mongoose迁移框架,它提供了mongoose连接的开箱即用。
在你的up
或down
function,你可以像这样访问你的模型
this('user').findOne({ name: 'Sergey' });
它还会将您的迁移保留到数据库而不是文件系统。
你也有东迁移框架是非常强大的,它也有mongoDB适配器: https : //github.com/okv/east
那么你将用命令来实现迁移:
east create my_migration_name
然后您的迁移脚本将如下所示:
exports.migrate = function(client, done) { var db = client.db; db......... done(); }; exports.rollback = function(client, done) { var db = client.db; db......... done(); };