Reliably reconnect to MongoDB

后端 未结 7 879
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 19:24

UPDATE: I am using the 2.1 version on the driver, against 3.2

I have a node application that uses MongoDB. The problem I have is that if the MongoDB

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 19:43

    If you was using Mongoose for your Schemas, it would be worth considering my option below since mongoose was never retrying to reconnect to mongoDB implicitly after first attempt failed.

    Kindly note I am connecting to Azure CosmosDB for MongoDB API. On yours maybe on the local machine.

    Below is my code.

    const mongoose = require('mongoose');
    
    // set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
    mongoose.set('useNewUrlParser', true);
    // In order to use `findOneAndUpdate()` and `findOneAndDelete()`
    mongoose.set('useFindAndModify', false);
    
    async function mongoDbPool() {
    // Closure.
    return function connectWithRetry() {
        // All the variables and functions in here will Persist in Scope.
        const COSMODDBUSER = process.env.COSMODDBUSER;
        const COSMOSDBPASSWORD = process.env.COSMOSDBPASSWORD;
        const COSMOSDBCONNSTR = process.env.COSMOSDBCONNSTR;
    
        var dbAuth = {
            auth: {
                user: COSMODDBUSER,
                password: COSMOSDBPASSWORD
            }
        };
        const mongoUrl = COSMOSDBCONNSTR + '?ssl=true&replicaSet=globaldb';
    
        return mongoose.connect(mongoUrl, dbAuth, (err) => {
            if (err) {
                console.error('Failed to connect to mongo - retrying in 5 sec');
                console.error(err);
                setTimeout(connectWithRetry, 5000);
            } else {
                console.log(`Connected to Azure CosmosDB for MongoDB API.`);
            }
        });
    };}
    

    You may decide to export and reuse this module everywhere you need to connect to db via Dependency Injection. But instead I will only show how to access the database connection for now.

    (async () => {
        var dbPools = await Promise.all([mongoDbPool()]);
        var mongoDbInstance = await dbPools[0]();
    
        // Now use "mongoDbInstance" to do what you need.
    })();
    

提交回复
热议问题