Working with Node.js(monogdb, express and other modules)
I'm wondering if there is a mongoose method for database connection, something like if I open a connection var db = mongoose.connect('mongo://localhost/members');
then I can db.on('close', function(){ /*do stuffs here*/})
.
Basicly, the function below does the job of getting a user list from database and logging when database connection is closed.
So I need something in the if()
to check database connection or whatever just unable to get data while its off and make a logging. I tried if(docs != null)
it seems just off tho. Any advice would be much appreciated!
var logger = require('bunyan');
var log = new logger({
name: "loggings",
streams: [
{
level: 'error',
path: 'test.log',
}
],
serializers: {
err: logger.stdSerializers.err,
}
});
function(req, res){
memberModel.find(function(err, docs){
if (/*connection is closed*/) {
res.render('users.jade', { members: docs });
}else{
try {
throw new DatabaseError ("Error!");
} catch (err){
log.warn({err: err}, "Check database connection!");
}
res.render('index.jade');
};
});
};
Why are you checking in the place you are for the database connection being closed? If it is closed at that point, then it is likely that docs will be null. I think checking
if (!err) {
res.render('users.jade', { members : docs });
} else {
/* throw err, etc */
is a reasonable course to take.
Since you want to log when the database connection is closed, why not attach a logging function to the Db's "close" event?
If I've misunderstood and checking for the connection's state is what you really want, then I'd recommend playing around with the properties of:
http://mongoosejs.com/docs/api.html#connection_Connection
(hit the "show code" button). The connection's _closeCalled property looks like it may be what you want to check.