有没有人有用mongoose插件迁移mongodb数据的迁移模块?
我目前正在使用'migrate‘模块,它工作得很好,除了我需要在每个up/down中创建/销毁我的连接。
也就是说。
// 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
});
});
};这可能是一种更好的方法。我想知道是否唯一的选择是创建我自己的模块,该模块只启动一次连接,并在所有补丁完成时关闭它。
我见过在数据库集合中跟踪迁移的mongoose-migrate。不是真正特定于mongoose IMHO,我宁愿仍然使用.migrate文件,但只需打开连接一次。
发布于 2014-12-31 05:37:56
这个问题的原因是你每次迁移的时候都有连接“连接”,这就是为什么你必须断开连接。如果将connect替换为mongoose.createConnection,也会出现同样的情况。您将需要关闭它。
如何解决?
移动
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')因此,您将拥有:
中的干净代码
发布于 2016-04-06 09:45:10
您也可以尝试我的migrate-mongoose迁移框架,它提供了开箱即用的mongoose连接。
在您的up或down函数中,您可以像这样访问模型
this('user').findOne({ name: 'Sergey' });它还会将您的迁移保存到数据库中,而不是文件系统中。
发布于 2017-05-01 21:00:39
你还有一个非常强大的east迁移框架,它也有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();
};https://stackoverflow.com/questions/17410020
复制相似问题