I was trying to disconnect the mongoose connection after finishing the database work, but seems it didn't work
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myDatabase');
var MyModel = mongoose.model('MyModel', MySchema);
//do something here
mongoose.disconnect();
The first time everything works fine, but when run the code for the second time, i get the error "Trying to open unclosed connection". I also tried mongoose.connection.close(); and got the same result.
Could anyone please help me with this?
Thank you very much!
Gary
I think i figured this out.
In my code, i was trying to do something with my model with the database:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myDatabase');
var MyModel = mongoose.model('MyModel', MySchema);
MyModel.findOne({}, function () {...});
mongoose.disconnect();
See the problem? Due to Nodejs's non-blocking feature, the "disconnect" was executed before "findOne" was completed, so of course it didn't work!
The solution is to put the disconnect into the callback function:
MyModel.findOne({}, function () {
...
mongoose.disconnect();
});
You do need to call mongoose. disconnect() to close the connection, but you also need to wait until all save calls have completed their async work (i.e. called their callback) before doing that.
Mongoose will try to connect with the MongoClient internally and return the instance of mongoose. this is the internal process of "conn. openUri" function and mongoose will execute the function. you can also connect the mongoClient directly without using mongoose.
connect() and mongoose. createConnection() , particularly in general what are the things to considered when using one over another. My understanding on the official documentation is that generally when there is only one connection mongoose. connect() is use, whereas if there is multiple instance of connection mongoose.
You don't handle a Promise with a callback: mongoose call you're callback if provided, otherwise it return the Promise.
try like this:
var db = mongoose.connect('mongodb://localhost:27017/myDatabase');
MyModel.findOne({}, function () {
// todo
db.disconnect();
});
var db = mongoose.createConnection('mongodb://localhost:27017/myDatabase');
MyModel.findOne({}, function () {
// Processing to be done
db.close();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With