Reputation: 1011
I am using Mongoose. I have two Mongo DB Server i.e
Primary(27017, 27018, 27020 {replica set enabled on primary}) & Secondary(27021)
Now I want to interact with these two server through API in nodejs. Lets say
router.post('/connectToDB1', function (req, res) {
//Some logic for interacting with DB 1
})
router.post('/connectToDB2', function (req, res) {
//Some logic for interacting with DB 2
})
On my node server what I implemented is like this:
//On my app.js File
var Mongoose = require('mongoose').Mongoose;
Mongoose.Promise = global.Promise;
var Message = require('./models/message');
var mydb1;
var mydb2;
var instance1 = new Mongoose();
var uri1 = 'mongodb://127.0.0.1:27017, 127.0.0.1:27018, 127.0.0.1:27020/myDBName?replicaSet=newRep';
instance1.connect(uri1, { useMongoClient: true }).openUri(uri1, function (errr,db) {
if (errr) {
throw errr;
} else {
console.log("Primary Connection Successfull");
mydb1 = instance1;
}
});
var instance2 = new Mongoose();
var uri2 = 'mongodb://127.0.0.1:27021/secondary';
instance2.connect(uri2, { useMongoClient: true }).openUri(uri2 , function (errr,db) {
if (errr) {
throw errr;
} else {
console.log("Secondary Connection Successfull");
mydb2 = instance2;
}
});
Now I don't Know how to Interact/create A Query...
Any help is really Apreciated.
Upvotes: 0
Views: 944
Reputation:
Mongoose has a function called createConnection() that returns a connection object. You can create multiple connections to different servers/replicaSets and create models specific to each connection. Here is an example:
49790706.js
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
const conn1 = mongoose.createConnection('mongodb://localhost:27017/test1');
const conn2 = mongoose.createConnection('mongodb://localhost:27018/test2');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String
});
const adminSchema = new Schema({
name: String
});
const User = conn1.model('User', userSchema);
const Admin = conn2.model('Admin', adminSchema);
const billy = new User({ name: 'Billy' });
const root = new Admin({ name: 'root' });
async function run () {
await conn1.dropDatabase();
await conn2.dropDatabase();
await billy.save();
await root.save();
let b = await User.find({});
let r = await Admin.find({});
console.log('users:', b);
console.log('admins:', r);
return mongoose.disconnect();
}
run();
shell output
stack: ./49790706.js
users: [ { _id: 5acf1b72bb7d5f546c1a526f, name: 'Billy', __v: 0 } ]
admins: [ { _id: 5acf1b72bb7d5f546c1a5270, name: 'root', __v: 0 } ]
stack:
You need to be sure that when you create your models you attach them to the specific relevant connection, ie conn1.model(..)
. Also, when your app is ready to close the connections rather than call .close()
on each one, note that you can call mongoose.disconnect()
and it will close all connections in parallel.
Upvotes: 2