my app.js contains,
exports.getDatabaseConnection = function (dbname, uname, psw) {
mongoose.disconnect();
mongoose.connect('mongodb://' + uname + ':' + psw + '@localhost:27017/' + dbname);
}
and index.js is
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 i connect to india then it works fine but second time when i call an chooseDb api with finland it gives an error like, Error: Trying to open unclosed connection. for mongoose.createConnection i 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 an error db.model is not function
Connect using--
mongoose.createConnection('mongodb://' + uname + ':' + psw + '@localhost:27017/' + dbname)
and not connect()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.