node.js - how to reconnect mongoose default connection? -
my app.js contains,
exports.getdatabaseconnection = function (dbname, uname, psw) { mongoose.disconnect(); mongoose.connect('mongodb://' + uname + ':' + psw + '@localhost:27017/' + dbname); }
and 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'); } })
when first connect india works fine second time when call choosedb api finland gives error like, error: trying open unclosed connection. mongoose.createconnection tried schema like
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);
which gives me error db.model not function
connect using--
mongoose.createconnection('mongodb://' + uname + ':' + psw + '@localhost:27017/' + dbname)
and not connect()
.
Comments
Post a Comment