Simple way to have a single connection to mongodb in your app by using require
Ever had to build a Node app that required you to:
- Connect to MongoDB multiple times
- Pass an object into all of the files (for example the app object in Express)
The MongoDB Driver for Node.js doesn't need to make multiple connections from the same app. You can actually use the same object through out your whole app. With Mongo Singleton you can require your db on every file and it will hold the reference of the same DB object through the whole application.
//app.js - Set everything up for the first timerequire'mongo-single'processenvMONGO_URL; //Set the connection but don't verify for errors or anything// orrequire'mongo-single'processenvMONGO_URL //Set and obtain the connection and inspect for errorsconsole.logarguments;;
//model.jsdb = require'mongo-single'processenvMONGO_URL; //Obtian the connection
Simple as that. If your URL for the db object changes, it will also be cached. Therefore your connections will always be available to be required as long as you keep the same URL.
You can also pass in a object containing the options for the connection. This is not required but recommended.
require'mongo-single'processenvMONGO_URL native_parser: true; //Set the connection but don't verify for errors or anything
Feel free to submit pull requests and stuff.