I have an app with MongoDB as backend. When the app is started, I set up the connection and use it later on requests.
But if in the mean time my db conncetion fails (ie. mongod crashes), how can I check that on the request time?
To clarify a bit:
db.once('open', function../* setup */)
db.find(conditions, function(err, res) { if (err) ...else ...})
.What I want to do is check if the connection is alive before the db.find()
clause. So if it is down, I can try to restart the db connection.
P.S. I know, I should probably set some sort of a connection pool or similar instead of keeping the connection alive all the time, but right now it's set as it is.
You can use event to handle it as callback.
And maybe have your global variable that will identify that it is not connected.
You can have separate db.js
file, that will behave as module. And you can have function to get collection from it.
var mongodb = require('mongodb');
var client;
var collections = { };
new mongodb.Db( ... ).open((function (err, c) {
if (!err) {
client = c;
client.on('close', function() {
client = null; // clear client
collections = { }; // clear old collections
// connection closed
});
} else {
// error connecting
}
});
// get collection
exports.get = function(name, callback) {
if (client) {
if (!collections[name]) {
collections[name] = new mongodb.Collection(client, name);
}
callback(null, collections[name]);
} else {
// can perform reconnecting and then get collection and call callback
callback(new Error('not connected'));
}
}
So to use it:
var db = require('./db.js');
db.get('users', function(err, collection) {
if (!err) {
collection.find({ ...
} else {
console.log(err);
}
});
Sorry, just noticed you are using Mongoose, which can be different slightly.
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