简体   繁体   中英

Handing MongoDB connection issues from Node (Express)

I have an Express App which connects to a MongoDB server at startup and serves requests on-demand (I don't disconnect - it's a single threaded server so no pooling - fairly simple stuff)

Problem is that it's possible the MongoDB server will be unavailable for periods of time (it's not on-site) and whilst the Express App doesn't crash, it seems that any requests made to the server will run indefinately until the connection is restored!

I'd like to limit that (eg throw an error back after a period of time) but I can't seem to make that happen...

I'm using connect options "{server: {auto_reconnect: true}}" which seems to ensure that once the MongoDB server reappears, requests complete (without it, requests made during downtime seem to run forever...) - and I don't have access to the client code so I can't fix it there...

I'd assumed a combination of 'connectTimeoutMS' or 'socketTimeoutMS' would allow me to terminate requests when MongoDB is unavailable for longer periods, but I just can't get those to work (I've tried them as connect options, passing them in the URI etc. etc.)

Any attempt to open a Collection and Find/Insert/Update just 'hangs' until the MongoDB reappears - I've left it over 30 mins and everything was just sitting these (and completed AOK when the network was restored!)

What's the best way around this? Should I open a connection specifically for each request (not really a performance issue - it's not a high volume app) or is there something else I'm missing?

Updated to add the connect code

var myDB
var mongodb = require('mongodb')
var uri = // some env vars and stuff
mongodb.MongoClient.connect(uri, {server: {auto_reconnect: true}}, function (err, db) {
 myDB = db
})

myDB is then used elsewhere to open collections - and the handle from that is used to find/insert etc.

If the connection to the DB is interrupted, myDB.collection() calls (or calls to find/insert on their handles) will simply hang until the connection is restored - nothing I've tried will cause them to 'time out' sooner!?

I assume that you are using mongoose as a driver.

You'd catch the error by this.

var db = require('domain').create();

db.on('error', function(err) {
    console.log('DB got a problem');
});

db.run(function() {
    mongoose.connect(config, options);
});

or you can directly access

mongoose.connection.readyState

to check the statement of your DB.

Connection ready state

0 = disconnected

1 = connected

2 = connecting

3 = disconnecting

Each state change emits its associated event name.

http://mongoosejs.com/docs/api.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM