猫鼬迁移

los*_*ion 6 migrate mongoose mongodb node.js

任何人都有一个迁移模块,用于使用mongoose插件迁移mongodb数据?

我目前正在使用"迁移"模块,除了我需要在每个向上/向下创建/销毁我的连接这一事实之外,它工作得很好.

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
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

可能是一个更好的方法来做到这一点.想知道唯一的选择是创建我自己的模块,启动连接一次,并在所有补丁完成后关闭它.

我见过mongoose-migrate跟踪数据库集合中的迁移.不是特定于猫鼬恕我直言,我宁愿仍然使用.migrate文件,但只需要打开一次连接.

小智 2

问题的原因是您每次迁移时都“连接”连接,这就是您必须断开连接的原因。如果将 connect 替换为 mongoose.createConnection,也会出现同样的情况。你需要关闭它。

怎么解决?

移动

  var mongoose = require('mongoose')
       , Role = require('../models/role')
       , User = require('../models/user');
Run Code Online (Sandbox Code Playgroud)

进入像 db 这样的模块

var mongoose = require('mongoose')
      , Role = require('../models/role')
      , User = require('../models/user');
module.exports = mongoose      
Run Code Online (Sandbox Code Playgroud)

只需要它

      var mongoose = require('./db')
Run Code Online (Sandbox Code Playgroud)

所以你将拥有:

  • 单连接
  • 所有模型均加载到一处
  • 迁移中的干净代码