简体   繁体   中英

How to deal with connection lost to DB in NodeJS Express App

I am developing an express application which connects to a MongoDB database. It is possible that my express server looses the connection to database, but how should my express server react to this scenario? I prepared the following code where i check for a lost connection and then I kill the app.

const registerCustomer = async (req, res) => {
    let validRegistrationCode;
    try {
        validRegistrationCode = await CustomerRegistrationCode.findOne({ code: req.body.code });
    } catch (error) {
        if (error instanceof MongoNetworkError || error instanceof MongooseServerSelectionError) {
            console.error('Mongo | Mongoose Network Error occurred');
        }
        process.exit(1);
    }
    return res.json({ obj: validRegistrationCode });
}

For every access to the DB, I have to check for a connection error and I think this makes the code ugly. How can this be improved?

I think the failure of connection to mongoDB usually doesn't happen or it can also happen in case of network is loss, or your path, syntax is not correct and what you should do is check only once when setup mongoose to connect to your database, every time you save code nodemon will help you check if you have successfully connected

 // connect model with database const mongoose = require('mongoose'); async function connect() { try { await mongoose.connect('mongodb://localhost:27017/collections_clothes', { // useNewUrlParser: true, // useUnifiedTopology: true, // useCreateIndex: true, }); console.log("Access Database Success!"); } catch (error) { console.log("Access FAIL!"); } } module.exports = { connect };

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