Access multiple mongo databases with mongoose - node.js

From within a single nodejs app, how can I switch between mongodb instances?
For some context, I'm writing a queue worker with nodejs/zeromq/mongoose.
I have multiple nodejs/mongo apps running on the same server, each with their own mongo database, push jobs to a queue.
My worker app pulls and processes the jobs sequentially.
Depending which app sent the job, it needs to connect to the appropriate mongo database through mongoose. All apps use the same mongoose models, so the same models are already available in my worker app.
I'm having trouble switching connections and I'm afraid listing the details of my attempts/results would muddy up the question here.
It doesn't matter if it's limited to 1 at a time, or if I maintain a collection of connections.
Any insight would be appreciated.

Use createConnection. See the docs Here: http://mongoosejs.com/docs/api.html. I haven't done it myself, but I believe you then just create models attached to each schema
var mongoose = require('mongoose');
var db = mongoose.createConnection(..);
db.model('Venue', new Schema(..));
var Ticket = db.model('Ticket', new Schema(..));
var Venue = db.model('Venue');

Related

Switch DB dynamically for NodeJS web application

I am trying to implement a feature which a user can decide on login to which DB to connect. As it is a web-app, running on a server which all the clients approach, how can I implement this feature without changing every client DB?
At our company we are using mongoose as the MongoDB API.
I read all the docs, and didn't notice any functionality for using multiple connections to different DB's on different hosts within the same App at once - without damaging other's client work.
The most valuable thing I have accomplished is to open few connections based on multiple mongoose instances, based on this post:
Mongoose and multiple database in single node.js project
I have created few files for example:
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://10.20.100.71:27017/DB_NAME');
module.exports = exports = mongoose;
And then I required them:
let stageAccess = require('./databsesConnections/stageAccess');
let prodAccess = require('./databsesConnections/prodAccess');
I debugged the files and checked the connections are establishing.
Further more I checked in the mongoose docs and concluded that I can choose which connection is the default connection, as the docs state:
"Mongoose creates a default connection when you call mongoose.connect(). You can access the default connection using mongoose.connection."
So I tried:
mongoose.connection = mongoose.connections[1];
And it works fine.
So the actual question is, what will happen if client 1 approach the app, select to connect dbNum1 and starts to work,
then client 2 approach the app and select to connect to dbNum2?

MongoDB connections on require or by function

I am working on a single pager that writes to different mongodb databases through an API setup with express. To do this I have one file named db.js that is doing all of the work with the mongoose module and then exporting the two connections to my express file called app.js.
When I start running my app file with node, my mongo console shows the two connections being made.
My question is, should I be making the exports structured so that they are functions that only connect to the DB when the functions themselves are called? Is there anything bad about leaving the two connections open and waiting for people to use them?
It is better to have your database connections created on start of the application, and leaving them open. The other way to create connections when an API call is made is extremely inefficient, because the connection load increases wrt number of API calls, and also because the response time of the API increases.
In db.js export your objects.
In your app.js, you can directly require the appropriate connection and start using it
var db = require("../db").first;
db.find({}, function (err, res) {})

How to listen for updates in mongodb with websockets

I'm trying to set up a notification system for my web app. Currently, I want to add an extra field to my mongo db, and have this update my front end in real time using socket.io
I know previously mongo had no functionality for listening to updates in its database - but has anything been recently released? Or is there another option to database triggers?
You can use Change Streams which is supported in many languages.
Since you are using socket.io you can see the node.js implementation
const collection = db.collection('inventory');
const changeStream = collection.watch();
changeStream.on('change', next => {
// process next document
});
Here is the link: https://docs.mongodb.com/manual/changeStreams/

How to check if there is an existing MongoDB connection using mongoose?

I have an express app that connects to MongoDB via mongoose, and I also have an init script that will occasionally connect to MongoDB.
Is there any way to detect if there is an existing connection to the DB, so I will not need to connect again in the script anytime I want to run it, also is there any consequences for connecting to the DB multiple times via mongoose.
you can check this using mongoose.connection.readyState,
ex.
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
The state would return 1 if already connected.
You can check the readyState
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);

Does Mongoose allow for Multiple Database Connections?

I read that in a nodejs application, if we use a mongoose object using
var obj = require('mongoose');
then, wherever we create a new mongoose object (say, in another file), then the same cached copy is used throughout. In that case, how can we connect to multiple database instances of mongoDB in the same nodejs app ?
You can use mongoose.createConnection to connect to a separate database, and then using the connection object that generates, you can define models from that database using connection.model.

Resources