3

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:sync@ds143542.mlab.com:');
    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);
Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103
  • hmmm I always wondered how to make more than 1 connections with mongoose... can you show your code regarding how you actually make multiple connections? –  Nov 21 '17 at 02:30
  • check the `.connections` it contains your db instances. – Jalil Nov 21 '17 at 02:31
  • making multiple connections with mongoose: https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project –  Nov 21 '17 at 02:31
  • @Jalil why make it vague? you mean `mongoose.connections` right? –  Nov 21 '17 at 02:32
  • I Updated My Code, I want to Check 2 Connection and after that sync local to mlab, Oleqzandr multiple connection in mongoose in defferet (http://mongoosejs.com/docs/connections.html) I Couldn't solve with this: `mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);` – Saeed Heidarizarei Nov 21 '17 at 02:42
  • yes I mean `mongoose.connections` it is an array that contains all your db instances. – Jalil Nov 21 '17 at 02:43
  • Can you Edit with my Code Please? – Saeed Heidarizarei Nov 21 '17 at 02:44

1 Answers1

2

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'));
});
DoloMike
  • 499
  • 6
  • 15