Error after connecting to multiple databases in meteor mongodb

We are using different databases to store user’s data. For example, user’s general information (login, password, profile info, etc) stored in the meteor database, but if the user has own contacts, tasks or other information, they will be stored at the separate databases created for each user based on id.
Connection to the database looks like this:

var userId = this.userId;
var database = new MongoInternals.RemoteCollectionDriver(‘mongodb://localhost:27017/’ + userId);
var collection = database.open(‘tasks’);

Generally, it works even at the production stage but sometimes Meteor fails to connect to other databases.

I"Error: write EPIPE" & “MongoError: connection to example.com:27017 closed”).

So we don’t know why this error occurs.

Here is the screenshot of the logs we’ve got after failing to connect: https://image.ibb.co/eR74K6/Screen_Shot_2018_01_06_at_11_30_26_AM.png

That’s most likely because you’re attempting to write to a closed socket. Are you explicitly closing the DB connection, or hoping it will be handled for you? With multiple users, the server code will be keeping lots of databases open, even if they’re no longer being used. That’s likely to eat memory and may result in odd issues like this.

1 Like

Currently we are using db.open(“collectioName”) for each remote collection whenever db operations are needed to be done. I guess this operation creates a new connection each time therefore this issue happens. is there any way to open connection to user’s database only once and access collections when needed?