Hello @Harsha_Buggi,
Can you please try the demo that I have provided on GitHub, Sorry I did not explain the code here, let me do that first,
You have to use the createConnection
method to connect with the specific MongoDB server, where I have created a common connect.js
file to reuse this code for the second MongoDB server connection.
This will return a connection object when you import it in the main file.
const mongoose = require("mongoose");
module.exports = (name, connString) => {
const db = mongoose.createConnection(connString);
db.on('connected', () => {
console.info(`${name} MongoDB connection succeeded!`);
});
db.on('error', (err) => {
console.error(`${name} MongoDB connection failed, ` + err);
db.close();
});
db.on('disconnected', () => {
console.info(`${name} MongoDB connection disconnected!`);
});
process.on('SIGINT', () => {
mongoose.connection.close().then(() => {
winston.info(`${name} Mongoose connection disconnected through app termination!`);
process.exit(0);
});
});
// EXPORT DB OBJECT
return db;
}
Let’s move to the main index.js
file, Update you constants
// UPDATE YOUR DEFAULTS
const firstDB = {
name: "First", // whatever for display purpose in console
connStr: "your first db connection url",
db: "mydb",
coll: "mycoll"
};
Let’s import connect file and connect your first db,
// CONNECT DB
const firstConn = require("./connect")(firstDB.name, firstDB.connStr);
Create model and schema, as you said you have different schemas for both collections so this will create a nonstrict schema, by providing empty {}
schema property and strict: false
in schema options. and the useDB
method will select the database for real-time operations
// CREATE MODEL & SCHEMA
const FirstSchema = firstConn.useDb(firstDB.db).model(
firstDB.coll,
new mongoose.Schema({}, { strict: false, collection: firstDB.coll })
);
Now you can do any operation by the above schema object, as I did insert the operation,
// DO TRANSACTIONS WITH SCHEMA
async function firstInsert() {
let doc = await FirstSchema.create({ name: "test", calledAt: new Date() });
console.log(doc);
}
firstInsert();
You can repeat the same steps that we did above for the second MongoDB server connection, you can see my code in GitHub that I have already done, and also I am adding here by combining them all together,
// UPDATE YOUR DEFAULTS
const secondDB = {
name: "Second", // for demo
connStr: "your second db connection url",
db: "mydb",
coll: "mycoll"
};
// CONNECT DB
const secondConn = require("./connect")(secondDB.name, secondDB.connStr);
// CREATE MODEL & SCHEMA
const SecondSchema = secondConn.useDb(secondDB.db).model(
secondDB.coll,
new mongoose.Schema({}, { strict: false, collection: secondDB.coll })
);
// DO TRANSACTIONS WITH SCHEMA
async function secondInsert() {
let doc = await SecondSchema.create({ name: "test", calledAt: new Date() });
console.log(doc);
}
secondInsert();