如何重新连接mongoose默认连接?

时间:2017-04-07 11:09:14

标签: node.js mongodb mongoose connection-string

我的app.js包含,

 exports.getDatabaseConnection = function (dbname, uname, psw) {
mongoose.disconnect();
     mongoose.connect('mongodb://' + uname + ':' + psw + '@localhost:27017/' + dbname);
    }

和index.js是

router.post('/chooseDb', function (req, res) {
      var temp = req.body.country;
      if (temp === "india") {
        var uname = 'abc';
        var psw = 'abc123';
        var dbname = 'demoDB';
        app.getDatabaseConnection(dbname, uname, psw);
        res.json('done');
      }
       else if (temp === "finland") {
    var uname = 'xyz';
    var psw = 'xyz123';
    var dbname = 'testDB';
    app.getDatabaseConnection(dbname, uname, psw);
    res.json('done');
  } 
    })

当我第一次连接到印度然后它工作正常但第二次当我用finland调用chooseDb api时它给出了一个错误,如, 错误:尝试打开未关闭的连接。 对于mongoose.createConnection,我尝试了类似

的模式
 var mongoose = require('mongoose'); 
    var schema = mongoose.Schema; 
    var db=require('../app.js'); 
    var garageSchema = new schema({ id: String, name: String, address: String }); 
module.exports = db.model('garage', garageSchema); 

这给了我一个错误 db.model不是功能

1 个答案:

答案 0 :(得分:0)

使用 -

连接
mongoose.createConnection('mongodb://' + uname + ':' + psw + '@localhost:27017/' + dbname)

而不是connect()