One Single Collection per Application

Hi All,

I’ve done this course and got some basic understanding. Now I have a question, can I use one collection object across the application.

The below code is from mongo documentation. From the below code, can I have this line collection = db.collection(“replicaset_mongo_client_collection”); under db = database;

var express = require(‘express’);
var mongodb = require(‘mongodb’);
var app = express();

var MongoClient = require(‘mongodb’).MongoClient;
var db;

// Initialize connection once
MongoClient.connect(“mongodb://localhost:27017/integration_test”, function(err, database) {
if(err) throw err;

db = database;

// Start the application after the database connection is ready
app.listen(3000);
console.log(“Listening on port 3000”);
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
db.collection(“replicaset_mongo_client_collection”).find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});

Hi @Sriharsha_72933,

I believe yes. But give me some time and let me confirm that for you.

Kanika

In the spirit of learning and figuring things out, why don’t you give it a try and let us know the outcome?

1 Like

Hi Brown,

I already tried, it’s working fine. But after couple of days the connection got broke and for every request to Mongodb I’m getting mongoerror saying topology got destroyed. So wondering if that’s because of making collection object global to the js file and using for all the methods.

Thanks

Sriharsha Tumati

Hi @Sriharsha_72933,

I have not seen your code, and would love to see how you were handling the global connection in your file.

Also, I found this link, maybe its helpful for you:

Kanika

In the above code, I’ve made collection object (“col”) as global. Now it’s common across the application. I can have “n” number of routes using the same “col” object to perform mongo operations. Is it best way of doing it?

In the link you provided, they are making connection as global which is good. But I thinking to make collection object as global and want to know the pros and cons.

Thanks for your support in advance…

Thanks
Sriharsha Tumati

Hi @Sriharsha_72933,

I maybe wrong here, so correct me below if I am wrong:

In my understanding, global variables in nodeJS have a scope of a module. Meaning if you have a single module, have a global variable and using it in different routes, it will work.

Source: https://itnext.io/how-to-share-a-single-database-connection-in-a-node-js-express-js-app-fcad4cbcb1e

Does this help?

Kanika