Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose and multiple database error handling

I have 2 Databases, 1: in local and 2: in mlab, and with this Code I Can Check error for one of databases if my Connection has a Problem.

mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
mongoose.Promise = global.Promise;

const db = mongoose.connection;

db.on('error', console.error);
db.once('open', () => {
    console.log(rangi.green('Connected To MongoDB'));
});

module.exports = db;


cron.schedule('1 * * * *', () => {
    const sync = mongoose.createConnection('mongodb://sync:[email protected]:');
    const remoteList = sync.model('User');
    remoteList.find({}, (err, docs) => {
        User.collection.insert(docs, status)
    })

    function status(err, result) {
        if (err && err.code == 11000) {
            console.log(rangi.red(`Err`));
        } else {
            console.info(rangi.magenta(`Sync Successful!`));
        }
    }
});

How Can I Check connection for My Second database?
How to add Multi-mongos support or Multiple connections and Error handling for That?

mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
like image 291
Saeed Heidarizarei Avatar asked May 16 '26 05:05

Saeed Heidarizarei


1 Answers

You may be looking for something like the following:

var localConnectStr = 'mongodb://localhost/test'
var mlabConnectStr = 'mongodb://<dbuser>:<dbpassword>@ds123456.mlab.com:25716/<dbname>'

var db = mongoose.createConnection(localConnectStr, { useMongoClient: true });
var mlabdb = mongoose.createConnection(mlabConnectStr, { useMongoClient: true });

You'll of course want to use your actual mlab uri and database user/pass. But this is how you would handle multiple connections. See createConnection here.

You could use the code you have, checking your local connection, to check mlab.

mlabdb.on('error', console.error);
mlabdb.once('open', () => {
    console.log(rangi.green('Connected To Mlab MongoDB'));
});
like image 115
DoloMike Avatar answered May 17 '26 18:05

DoloMike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!