Why am I getting error “Trying to open unclosed connection.”?

旧城冷巷雨未停 提交于 2019-11-30 07:53:39

In my opinion, you are trying to create another connection without closing the current one. So, you might want to use:

createConnection() instead of connect().

In your case, it would look like this:

db = mongoose.createConnection('mongodb://localhost/mydb');
Prolasis

I had the same issue and found that I had the below connection in another file, which was the reason why I couldn't connect with a different database name. The below createConnection is needed:

db = mongoose.createConnection('mongodb://localhost/mydb');

What I had in another file:

db = mongoose.Connection('mongodb://localhost/mydb');

just use mongoose.connect('...'); once.

maybe in your root app.js or index.js file, not in every model or database related files if your are importing (including) them.

Anyways, if you still have doubt you can check it by:

var mongoose = require('mongoose'); 
var db = mongoose.connection;

db.once('connected', function() {
  console.log('mongoDB is connected');
});

shouldn't your

db.once('open', function () {

  var testA = new Test({ timestamp: Date() });

});

be

db.once('open', function () {

  var testA = new Time({ timestamp: Date() });

});

If "Test" is a different schema based on a different connection, that might affect i think

King Obi

I had the same issue, but it was due to a typo:

express-sessions instead of express-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!