Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB connection error handling with monk

I am using monk on a code that looks like

var monk = require('monk')
var db = monk('localhost/mydb')

if(!db){
  console.log('no connection')
}

when I run it, console logs 'no connection', but I would like to know why it is not connecting, (maybe see a stack trace' how do I do that?

like image 351
Alloys Avatar asked Jan 10 '23 05:01

Alloys


2 Answers

Per https://github.com/Automattic/monk/pull/142 monk('localhost') can now be used as a promise which resolves when the connection opens and rejects when it throws an error.

i.e.

let db = monk('localhost');

db.catch(function(err) {
  console.log(err)
});
like image 149
Derek Hill Avatar answered Jan 18 '23 14:01

Derek Hill


Hey I have been struggling with this and finally got a very beautiful solution regarding the same. So this a basic node philosophy where the callback has the first argument as the error object. Here in monk this holds good, the code that solves this problem is:

var monk = require('monk');
var db = monk('localhost/mydb', function(err, db){
    if(err){
       console.error("Db is not connected", err.message);
    }
});

As you see a callback function is passed to the monk object itself and that callback has parameters of our interests first being the err object and the next being the db object.

The err object contains all the information about the error that occurs while establishing the connection and corresponding message.

You can go on and look at the err and db object they actually give a deeper insight on how monk has handled things and what object does mongo DB has returned.

Hope this solves your problem.

like image 25
Farhaan Bukhsh Avatar answered Jan 18 '23 14:01

Farhaan Bukhsh