I want to create a module for NodeJS to connecto to MongoDB. I've seen that the new, better approach is to use MongoClient, but I can't get to know how can I make concurrent operations on the database. The goal I want to achieve is to have functions to abstract the database, like the following:
exports.insertItem(item){
//Whatever
}
According to the docs, I am supposed to connect to the database this way:
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, db) {
//Do stuff on the db object
});
The problem is how I am supposed to reuse the db object if it's not in a scope I can use to export functions in node? Am I supposed to make a MongoClient.connect() on every function that deals with the DB?
You make a single db connection and reuse it everywhere
A typical pattern for modules is
export.myinsert = function(db) {
return function(whatever) {
}
}
and then do
require('mymodule')(db)
Have a look at an example