Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 329
Hal Carleton Avatar asked Aug 11 '14 19:08

Hal Carleton


1 Answers

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'); 
like image 188
lvarayut Avatar answered Sep 28 '22 13:09

lvarayut