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

守給你的承諾、 提交于 2019-11-29 10:41:28

问题


I am trying to connect my node app to mongodb via mongoose. It seems to be working, as I can add documents, but I get the error { [Error: Trying to open unclosed connection.] state: 2 }.

I created a very simple app, just to make sure everything is working properly before connecting my actual app.

Here is my simple app:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var timeSchema = new Schema({ timestamp: String });
var Time = mongoose.model('Time', timeSchema);

mongoose.connect('mongodb://localhost/mydb');

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function () {

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

});

I also tried adding db.close() to the end, but it made no difference.

This is running on a Ubuntu 14.04 VPS with:

  • Node.js v0.10.3
  • MongoDB 2.6.3
  • Mongoose 1.4.21

回答1:


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');



回答2:


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');



回答3:


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');
});



回答4:


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




回答5:


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

express-sessions instead of express-session



来源:https://stackoverflow.com/questions/25250544/why-am-i-getting-error-trying-to-open-unclosed-connection

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