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