How to properly reuse connection to Mongodb across NodeJs application and modules










64














I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js (main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:



 var MongoClient = require('mongodb').MongoClient;
var mongo = ; // this is passed to modules and code

MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db)
if (!err)
console.log("We are connected");

// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");

console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

else
console.log(err);
);

var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined


then another module models/user looks like that:



Users = function(app, mongo) 

Users.prototype.addUser = function()
console.log("add user");


Users.prototype.getAll = function()

return "all users " + mongo.dbUsers;




module.exports = Users;


Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?










share|improve this question























  • The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
    – Salvador Dali
    Jul 8 '14 at 1:22










  • Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like module.exports = mongoist(connectionString);. (Read about connectionString in MongoDB Manual.)
    – Alexandr Nil
    Oct 1 '17 at 19:37















64














I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js (main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:



 var MongoClient = require('mongodb').MongoClient;
var mongo = ; // this is passed to modules and code

MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db)
if (!err)
console.log("We are connected");

// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");

console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

else
console.log(err);
);

var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined


then another module models/user looks like that:



Users = function(app, mongo) 

Users.prototype.addUser = function()
console.log("add user");


Users.prototype.getAll = function()

return "all users " + mongo.dbUsers;




module.exports = Users;


Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?










share|improve this question























  • The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
    – Salvador Dali
    Jul 8 '14 at 1:22










  • Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like module.exports = mongoist(connectionString);. (Read about connectionString in MongoDB Manual.)
    – Alexandr Nil
    Oct 1 '17 at 19:37













64












64








64


33





I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js (main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:



 var MongoClient = require('mongodb').MongoClient;
var mongo = ; // this is passed to modules and code

MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db)
if (!err)
console.log("We are connected");

// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");

console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

else
console.log(err);
);

var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined


then another module models/user looks like that:



Users = function(app, mongo) 

Users.prototype.addUser = function()
console.log("add user");


Users.prototype.getAll = function()

return "all users " + mongo.dbUsers;




module.exports = Users;


Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?










share|improve this question















I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js (main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:



 var MongoClient = require('mongodb').MongoClient;
var mongo = ; // this is passed to modules and code

MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db)
if (!err)
console.log("We are connected");

// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");

console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

else
console.log(err);
);

var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined


then another module models/user looks like that:



Users = function(app, mongo) 

Users.prototype.addUser = function()
console.log("add user");


Users.prototype.getAll = function()

return "all users " + mongo.dbUsers;




module.exports = Users;


Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?







javascript node.js mongodb express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 8 '14 at 6:39









tereško

52.2k2077135




52.2k2077135










asked Jul 8 '14 at 0:22









spirytusspirytus

3,71164967




3,71164967











  • The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
    – Salvador Dali
    Jul 8 '14 at 1:22










  • Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like module.exports = mongoist(connectionString);. (Read about connectionString in MongoDB Manual.)
    – Alexandr Nil
    Oct 1 '17 at 19:37
















  • The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
    – Salvador Dali
    Jul 8 '14 at 1:22










  • Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like module.exports = mongoist(connectionString);. (Read about connectionString in MongoDB Manual.)
    – Alexandr Nil
    Oct 1 '17 at 19:37















The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22




The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22












Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like module.exports = mongoist(connectionString);. (Read about connectionString in MongoDB Manual.)
– Alexandr Nil
Oct 1 '17 at 19:37




Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like module.exports = mongoist(connectionString);. (Read about connectionString in MongoDB Manual.)
– Alexandr Nil
Oct 1 '17 at 19:37












6 Answers
6






active

oldest

votes


















103














You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:



var MongoClient = require( 'mongodb' ).MongoClient;

var _db;

module.exports =

connectToServer: function( callback )
MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db )
_db = db;
return callback( err );
);
,

getDb: function()
return _db;

;


To use it, you would do this in your app.js:



var mongoUtil = require( 'mongoUtil' );

mongoUtil.connectToServer( function( err )
// start the rest of your app here
);


And then, when you need access to mongo somewhere, you can do this:



var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();

db.collection( 'users' ).find();


The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.



Note, code not tested.






share|improve this answer
















  • 6




    Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
    – Farhan Ahmad
    Feb 9 '15 at 2:59






  • 9




    How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
    – Ayan
    Aug 22 '17 at 12:02







  • 2




    I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
    – Keming
    Jan 17 '18 at 19:44






  • 2




    @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
    – Mike
    Feb 17 '18 at 21:40






  • 2




    As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
    – Julian Veerkamp
    Aug 23 '18 at 12:01


















9














If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.



Install



npm install --save express-mongo-db


server.js



var app = require('express')();

var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));


routes/users.js



app.get('/', function (req, res, next) 
req.db // => Db object
);





share|improve this answer




























    9














    Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.



    I put some comments in the code.




    ./db/mongodb.js




     const MongoClient = require('mongodb').MongoClient
    const uri = 'mongodb://user:password@localhost:27017/dbName'
    let _db

    const connectDB = async (callback) =>
    try
    MongoClient.connect(uri, (err, db) =>
    _db = db
    return callback(err)
    )
    catch (e)
    throw e



    const getDB = () => _db

    const disconnectDB = () => _db.close()

    module.exports = connectDB, getDB, disconnectDB



    ./index.js




     // Load MongoDB utils
    const MongoDB = require('./db/mongodb')
    // Load queries & mutations
    const Users = require('./users')

    // Improve debugging
    process.on('unhandledRejection', (reason, p) =>
    console.log('Unhandled Rejection at:', p, 'reason:', reason)
    )

    const seedUser =
    name: 'Bob Alice',
    email: 'test@dev.null',
    bonusSetting: true


    // Connect to MongoDB and put server instantiation code inside
    // because we start the connection first
    MongoDB.connectDB(async (err) =>
    if (err) throw err
    // Load db & collections
    const db = MongoDB.getDB()
    const users = db.collection('users')

    try
    // Run some sample operations
    // and pass users collection into models
    const newUser = await Users.createUser(users, seedUser)
    const listUsers = await Users.getUsers(users)
    const findUser = await Users.findUserById(users, newUser._id)

    console.log('CREATE USER')
    console.log(newUser)
    console.log('GET ALL USERS')
    console.log(listUsers)
    console.log('FIND USER')
    console.log(findUser)
    catch (e)
    throw e


    const desired = true
    if (desired)
    // Use disconnectDB for clean driver disconnect
    MongoDB.disconnectDB()
    process.exit(0)

    // Server code anywhere above here inside connectDB()
    )



    ./users/index.js




     const ObjectID = require('mongodb').ObjectID

    // Notice how the users collection is passed into the models
    const createUser = async (users, user) =>
    try
    const results = await users.insertOne(user)
    return results.ops[0]
    catch (e)
    throw e



    const getUsers = async (users) =>
    try
    const results = await users.find().toArray()
    return results
    catch (e)
    throw e



    const findUserById = async (users, id) =>
    try
    if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
    const results = await users.findOne(ObjectID(id))
    return results
    catch (e)
    throw e



    // Export garbage as methods on the Users object
    module.exports = createUser, getUsers, findUserById





    share|improve this answer




















    • is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
      – shanks
      May 16 '18 at 21:44










    • It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
      – agm1984
      May 17 '18 at 22:08


















    5














    go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.



    For example, mongoose is one of the most common. This is what we have in our initial server.js file :



    const mongoose = require('mongoose');
    const options = server: socketOptions: keepAlive: 1;
    mongoose.connect(config.db, options);


    This is everything what is needed to set it up. Now use this anywhere in your code



    const mongoose = require('mongoose');


    And you get that instance you set up with mongoose.connect






    share|improve this answer
















    • 1




      mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
      – Saras Arya
      Apr 13 '17 at 14:16






    • 1




      Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
      – agm1984
      Jul 24 '17 at 6:10


















    2














    Initialize the connection as a promise:



    const MongoClient = require('mongodb').MongoClient
    const uri = 'mongodb://...'
    const client = new MongoClient(uri)
    const connection = client.connect() // initialized connection


    And then call the connection whenever you wish you perform an action on the database:



     // if I want to insert into the database...
    const connect = connection
    connect.then(() =>
    const doc = id: 3
    const db = client.db('database_name')
    const coll = db.collection('collection_name')
    coll.insertOne(doc, (err, result) =>
    if(err) throw err
    )
    )





    share|improve this answer






























      0














      A tested solution based on the accepted answer:



      mongodbutil.js:






      var MongoClient = require( 'mongodb' ).MongoClient;
      var _db;
      module.exports =
      connectToServer: function( callback )
      MongoClient.connect( "<connection string>", function( err, client )
      _db = client.db("<collection name>");
      return callback( err );
      );
      ,
      getDb: function()
      return _db;

      ;





      app.js:






      var createError = require('http-errors');
      var express = require('express');
      var path = require('path');
      var cookieParser = require('cookie-parser');
      var logger = require('morgan');
      var app = express();
      app.set('views', path.join(__dirname, 'views'));
      app.set('view engine', 'ejs');
      app.use(logger('dev'));
      app.use(express.json());
      app.use(express.urlencoded( extended: false ));
      app.use(cookieParser());
      app.use(express.static(path.join(__dirname, 'public')));

      var mongodbutil = require( './mongodbutil' );
      mongodbutil.connectToServer( function( err )
      //app goes online once this callback occurs
      var indexRouter = require('./routes/index');
      var usersRouter = require('./routes/users');
      var companiesRouter = require('./routes/companies');
      var activitiesRouter = require('./routes/activities');
      var registerRouter = require('./routes/register');
      app.use('/', indexRouter);
      app.use('/users', usersRouter);
      app.use('/companies', companiesRouter);
      app.use('/activities', activitiesRouter);
      app.use('/register', registerRouter);
      // catch 404 and forward to error handler
      app.use(function(req, res, next)
      next(createError(404));
      );
      // error handler
      app.use(function(err, req, res, next) );
      //end of calback
      );

      module.exports = app;





      activities.js -- a route:






      var express = require('express');
      var router = express.Router();
      var mongodbutil = require( '../mongodbutil' );
      var db = mongodbutil.getDb();

      router.get('/', (req, res, next) =>
      db.collection('activities').find().toArray((err, results) =>
      if (err) return console.log(err)
      res.render('activities', activities: results, title: "Activities")
      );
      );

      router.post('/', (req, res) =>
      db.collection('activities').save(req.body, (err, result) =>
      if (err) return console.log(err)
      res.redirect('/activities')
      )
      );

      module.exports = router;








      share|improve this answer




















        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24621940%2fhow-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        103














        You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:



        var MongoClient = require( 'mongodb' ).MongoClient;

        var _db;

        module.exports =

        connectToServer: function( callback )
        MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db )
        _db = db;
        return callback( err );
        );
        ,

        getDb: function()
        return _db;

        ;


        To use it, you would do this in your app.js:



        var mongoUtil = require( 'mongoUtil' );

        mongoUtil.connectToServer( function( err )
        // start the rest of your app here
        );


        And then, when you need access to mongo somewhere, you can do this:



        var mongoUtil = require( 'mongoUtil' );
        var db = mongoUtil.getDb();

        db.collection( 'users' ).find();


        The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.



        Note, code not tested.






        share|improve this answer
















        • 6




          Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
          – Farhan Ahmad
          Feb 9 '15 at 2:59






        • 9




          How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
          – Ayan
          Aug 22 '17 at 12:02







        • 2




          I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
          – Keming
          Jan 17 '18 at 19:44






        • 2




          @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
          – Mike
          Feb 17 '18 at 21:40






        • 2




          As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
          – Julian Veerkamp
          Aug 23 '18 at 12:01















        103














        You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:



        var MongoClient = require( 'mongodb' ).MongoClient;

        var _db;

        module.exports =

        connectToServer: function( callback )
        MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db )
        _db = db;
        return callback( err );
        );
        ,

        getDb: function()
        return _db;

        ;


        To use it, you would do this in your app.js:



        var mongoUtil = require( 'mongoUtil' );

        mongoUtil.connectToServer( function( err )
        // start the rest of your app here
        );


        And then, when you need access to mongo somewhere, you can do this:



        var mongoUtil = require( 'mongoUtil' );
        var db = mongoUtil.getDb();

        db.collection( 'users' ).find();


        The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.



        Note, code not tested.






        share|improve this answer
















        • 6




          Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
          – Farhan Ahmad
          Feb 9 '15 at 2:59






        • 9




          How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
          – Ayan
          Aug 22 '17 at 12:02







        • 2




          I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
          – Keming
          Jan 17 '18 at 19:44






        • 2




          @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
          – Mike
          Feb 17 '18 at 21:40






        • 2




          As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
          – Julian Veerkamp
          Aug 23 '18 at 12:01













        103












        103








        103






        You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:



        var MongoClient = require( 'mongodb' ).MongoClient;

        var _db;

        module.exports =

        connectToServer: function( callback )
        MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db )
        _db = db;
        return callback( err );
        );
        ,

        getDb: function()
        return _db;

        ;


        To use it, you would do this in your app.js:



        var mongoUtil = require( 'mongoUtil' );

        mongoUtil.connectToServer( function( err )
        // start the rest of your app here
        );


        And then, when you need access to mongo somewhere, you can do this:



        var mongoUtil = require( 'mongoUtil' );
        var db = mongoUtil.getDb();

        db.collection( 'users' ).find();


        The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.



        Note, code not tested.






        share|improve this answer












        You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance:



        var MongoClient = require( 'mongodb' ).MongoClient;

        var _db;

        module.exports =

        connectToServer: function( callback )
        MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db )
        _db = db;
        return callback( err );
        );
        ,

        getDb: function()
        return _db;

        ;


        To use it, you would do this in your app.js:



        var mongoUtil = require( 'mongoUtil' );

        mongoUtil.connectToServer( function( err )
        // start the rest of your app here
        );


        And then, when you need access to mongo somewhere, you can do this:



        var mongoUtil = require( 'mongoUtil' );
        var db = mongoUtil.getDb();

        db.collection( 'users' ).find();


        The reason this works is that in node, when modules are require'd, they only get loaded/sourced once so you will only ever end up with one instance of _db and mongoUtil.getDb() will always return that same instance.



        Note, code not tested.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jul 8 '14 at 14:29









        go-oleggo-oleg

        14.4k33238




        14.4k33238







        • 6




          Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
          – Farhan Ahmad
          Feb 9 '15 at 2:59






        • 9




          How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
          – Ayan
          Aug 22 '17 at 12:02







        • 2




          I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
          – Keming
          Jan 17 '18 at 19:44






        • 2




          @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
          – Mike
          Feb 17 '18 at 21:40






        • 2




          As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
          – Julian Veerkamp
          Aug 23 '18 at 12:01












        • 6




          Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
          – Farhan Ahmad
          Feb 9 '15 at 2:59






        • 9




          How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
          – Ayan
          Aug 22 '17 at 12:02







        • 2




          I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
          – Keming
          Jan 17 '18 at 19:44






        • 2




          @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
          – Mike
          Feb 17 '18 at 21:40






        • 2




          As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
          – Julian Veerkamp
          Aug 23 '18 at 12:01







        6




        6




        Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
        – Farhan Ahmad
        Feb 9 '15 at 2:59




        Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
        – Farhan Ahmad
        Feb 9 '15 at 2:59




        9




        9




        How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
        – Ayan
        Aug 22 '17 at 12:02





        How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
        – Ayan
        Aug 22 '17 at 12:02





        2




        2




        I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
        – Keming
        Jan 17 '18 at 19:44




        I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
        – Keming
        Jan 17 '18 at 19:44




        2




        2




        @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
        – Mike
        Feb 17 '18 at 21:40




        @KemingZeng - you need to make sure that all modules that use mongoUtil are imported in app.js within the callback function of connectToServer. If you require them in app.js before _db is set, then you'll get undefined errors in the other modules.
        – Mike
        Feb 17 '18 at 21:40




        2




        2




        As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
        – Julian Veerkamp
        Aug 23 '18 at 12:01




        As of mongoDB version 4 it should be var database = mongoUtil.getDb(); database.db().collection( 'users' ).
        – Julian Veerkamp
        Aug 23 '18 at 12:01













        9














        If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.



        Install



        npm install --save express-mongo-db


        server.js



        var app = require('express')();

        var expressMongoDb = require('express-mongo-db');
        app.use(expressMongoDb('mongodb://localhost/test'));


        routes/users.js



        app.get('/', function (req, res, next) 
        req.db // => Db object
        );





        share|improve this answer

























          9














          If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.



          Install



          npm install --save express-mongo-db


          server.js



          var app = require('express')();

          var expressMongoDb = require('express-mongo-db');
          app.use(expressMongoDb('mongodb://localhost/test'));


          routes/users.js



          app.get('/', function (req, res, next) 
          req.db // => Db object
          );





          share|improve this answer























            9












            9








            9






            If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.



            Install



            npm install --save express-mongo-db


            server.js



            var app = require('express')();

            var expressMongoDb = require('express-mongo-db');
            app.use(expressMongoDb('mongodb://localhost/test'));


            routes/users.js



            app.get('/', function (req, res, next) 
            req.db // => Db object
            );





            share|improve this answer












            If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.



            Install



            npm install --save express-mongo-db


            server.js



            var app = require('express')();

            var expressMongoDb = require('express-mongo-db');
            app.use(expressMongoDb('mongodb://localhost/test'));


            routes/users.js



            app.get('/', function (req, res, next) 
            req.db // => Db object
            );






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jun 18 '17 at 6:25









            Mukesh ChapagainMukesh Chapagain

            17.9k1088104




            17.9k1088104





















                9














                Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.



                I put some comments in the code.




                ./db/mongodb.js




                 const MongoClient = require('mongodb').MongoClient
                const uri = 'mongodb://user:password@localhost:27017/dbName'
                let _db

                const connectDB = async (callback) =>
                try
                MongoClient.connect(uri, (err, db) =>
                _db = db
                return callback(err)
                )
                catch (e)
                throw e



                const getDB = () => _db

                const disconnectDB = () => _db.close()

                module.exports = connectDB, getDB, disconnectDB



                ./index.js




                 // Load MongoDB utils
                const MongoDB = require('./db/mongodb')
                // Load queries & mutations
                const Users = require('./users')

                // Improve debugging
                process.on('unhandledRejection', (reason, p) =>
                console.log('Unhandled Rejection at:', p, 'reason:', reason)
                )

                const seedUser =
                name: 'Bob Alice',
                email: 'test@dev.null',
                bonusSetting: true


                // Connect to MongoDB and put server instantiation code inside
                // because we start the connection first
                MongoDB.connectDB(async (err) =>
                if (err) throw err
                // Load db & collections
                const db = MongoDB.getDB()
                const users = db.collection('users')

                try
                // Run some sample operations
                // and pass users collection into models
                const newUser = await Users.createUser(users, seedUser)
                const listUsers = await Users.getUsers(users)
                const findUser = await Users.findUserById(users, newUser._id)

                console.log('CREATE USER')
                console.log(newUser)
                console.log('GET ALL USERS')
                console.log(listUsers)
                console.log('FIND USER')
                console.log(findUser)
                catch (e)
                throw e


                const desired = true
                if (desired)
                // Use disconnectDB for clean driver disconnect
                MongoDB.disconnectDB()
                process.exit(0)

                // Server code anywhere above here inside connectDB()
                )



                ./users/index.js




                 const ObjectID = require('mongodb').ObjectID

                // Notice how the users collection is passed into the models
                const createUser = async (users, user) =>
                try
                const results = await users.insertOne(user)
                return results.ops[0]
                catch (e)
                throw e



                const getUsers = async (users) =>
                try
                const results = await users.find().toArray()
                return results
                catch (e)
                throw e



                const findUserById = async (users, id) =>
                try
                if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
                const results = await users.findOne(ObjectID(id))
                return results
                catch (e)
                throw e



                // Export garbage as methods on the Users object
                module.exports = createUser, getUsers, findUserById





                share|improve this answer




















                • is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
                  – shanks
                  May 16 '18 at 21:44










                • It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
                  – agm1984
                  May 17 '18 at 22:08















                9














                Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.



                I put some comments in the code.




                ./db/mongodb.js




                 const MongoClient = require('mongodb').MongoClient
                const uri = 'mongodb://user:password@localhost:27017/dbName'
                let _db

                const connectDB = async (callback) =>
                try
                MongoClient.connect(uri, (err, db) =>
                _db = db
                return callback(err)
                )
                catch (e)
                throw e



                const getDB = () => _db

                const disconnectDB = () => _db.close()

                module.exports = connectDB, getDB, disconnectDB



                ./index.js




                 // Load MongoDB utils
                const MongoDB = require('./db/mongodb')
                // Load queries & mutations
                const Users = require('./users')

                // Improve debugging
                process.on('unhandledRejection', (reason, p) =>
                console.log('Unhandled Rejection at:', p, 'reason:', reason)
                )

                const seedUser =
                name: 'Bob Alice',
                email: 'test@dev.null',
                bonusSetting: true


                // Connect to MongoDB and put server instantiation code inside
                // because we start the connection first
                MongoDB.connectDB(async (err) =>
                if (err) throw err
                // Load db & collections
                const db = MongoDB.getDB()
                const users = db.collection('users')

                try
                // Run some sample operations
                // and pass users collection into models
                const newUser = await Users.createUser(users, seedUser)
                const listUsers = await Users.getUsers(users)
                const findUser = await Users.findUserById(users, newUser._id)

                console.log('CREATE USER')
                console.log(newUser)
                console.log('GET ALL USERS')
                console.log(listUsers)
                console.log('FIND USER')
                console.log(findUser)
                catch (e)
                throw e


                const desired = true
                if (desired)
                // Use disconnectDB for clean driver disconnect
                MongoDB.disconnectDB()
                process.exit(0)

                // Server code anywhere above here inside connectDB()
                )



                ./users/index.js




                 const ObjectID = require('mongodb').ObjectID

                // Notice how the users collection is passed into the models
                const createUser = async (users, user) =>
                try
                const results = await users.insertOne(user)
                return results.ops[0]
                catch (e)
                throw e



                const getUsers = async (users) =>
                try
                const results = await users.find().toArray()
                return results
                catch (e)
                throw e



                const findUserById = async (users, id) =>
                try
                if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
                const results = await users.findOne(ObjectID(id))
                return results
                catch (e)
                throw e



                // Export garbage as methods on the Users object
                module.exports = createUser, getUsers, findUserById





                share|improve this answer




















                • is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
                  – shanks
                  May 16 '18 at 21:44










                • It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
                  – agm1984
                  May 17 '18 at 22:08













                9












                9








                9






                Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.



                I put some comments in the code.




                ./db/mongodb.js




                 const MongoClient = require('mongodb').MongoClient
                const uri = 'mongodb://user:password@localhost:27017/dbName'
                let _db

                const connectDB = async (callback) =>
                try
                MongoClient.connect(uri, (err, db) =>
                _db = db
                return callback(err)
                )
                catch (e)
                throw e



                const getDB = () => _db

                const disconnectDB = () => _db.close()

                module.exports = connectDB, getDB, disconnectDB



                ./index.js




                 // Load MongoDB utils
                const MongoDB = require('./db/mongodb')
                // Load queries & mutations
                const Users = require('./users')

                // Improve debugging
                process.on('unhandledRejection', (reason, p) =>
                console.log('Unhandled Rejection at:', p, 'reason:', reason)
                )

                const seedUser =
                name: 'Bob Alice',
                email: 'test@dev.null',
                bonusSetting: true


                // Connect to MongoDB and put server instantiation code inside
                // because we start the connection first
                MongoDB.connectDB(async (err) =>
                if (err) throw err
                // Load db & collections
                const db = MongoDB.getDB()
                const users = db.collection('users')

                try
                // Run some sample operations
                // and pass users collection into models
                const newUser = await Users.createUser(users, seedUser)
                const listUsers = await Users.getUsers(users)
                const findUser = await Users.findUserById(users, newUser._id)

                console.log('CREATE USER')
                console.log(newUser)
                console.log('GET ALL USERS')
                console.log(listUsers)
                console.log('FIND USER')
                console.log(findUser)
                catch (e)
                throw e


                const desired = true
                if (desired)
                // Use disconnectDB for clean driver disconnect
                MongoDB.disconnectDB()
                process.exit(0)

                // Server code anywhere above here inside connectDB()
                )



                ./users/index.js




                 const ObjectID = require('mongodb').ObjectID

                // Notice how the users collection is passed into the models
                const createUser = async (users, user) =>
                try
                const results = await users.insertOne(user)
                return results.ops[0]
                catch (e)
                throw e



                const getUsers = async (users) =>
                try
                const results = await users.find().toArray()
                return results
                catch (e)
                throw e



                const findUserById = async (users, id) =>
                try
                if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
                const results = await users.findOne(ObjectID(id))
                return results
                catch (e)
                throw e



                // Export garbage as methods on the Users object
                module.exports = createUser, getUsers, findUserById





                share|improve this answer












                Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.



                I put some comments in the code.




                ./db/mongodb.js




                 const MongoClient = require('mongodb').MongoClient
                const uri = 'mongodb://user:password@localhost:27017/dbName'
                let _db

                const connectDB = async (callback) =>
                try
                MongoClient.connect(uri, (err, db) =>
                _db = db
                return callback(err)
                )
                catch (e)
                throw e



                const getDB = () => _db

                const disconnectDB = () => _db.close()

                module.exports = connectDB, getDB, disconnectDB



                ./index.js




                 // Load MongoDB utils
                const MongoDB = require('./db/mongodb')
                // Load queries & mutations
                const Users = require('./users')

                // Improve debugging
                process.on('unhandledRejection', (reason, p) =>
                console.log('Unhandled Rejection at:', p, 'reason:', reason)
                )

                const seedUser =
                name: 'Bob Alice',
                email: 'test@dev.null',
                bonusSetting: true


                // Connect to MongoDB and put server instantiation code inside
                // because we start the connection first
                MongoDB.connectDB(async (err) =>
                if (err) throw err
                // Load db & collections
                const db = MongoDB.getDB()
                const users = db.collection('users')

                try
                // Run some sample operations
                // and pass users collection into models
                const newUser = await Users.createUser(users, seedUser)
                const listUsers = await Users.getUsers(users)
                const findUser = await Users.findUserById(users, newUser._id)

                console.log('CREATE USER')
                console.log(newUser)
                console.log('GET ALL USERS')
                console.log(listUsers)
                console.log('FIND USER')
                console.log(findUser)
                catch (e)
                throw e


                const desired = true
                if (desired)
                // Use disconnectDB for clean driver disconnect
                MongoDB.disconnectDB()
                process.exit(0)

                // Server code anywhere above here inside connectDB()
                )



                ./users/index.js




                 const ObjectID = require('mongodb').ObjectID

                // Notice how the users collection is passed into the models
                const createUser = async (users, user) =>
                try
                const results = await users.insertOne(user)
                return results.ops[0]
                catch (e)
                throw e



                const getUsers = async (users) =>
                try
                const results = await users.find().toArray()
                return results
                catch (e)
                throw e



                const findUserById = async (users, id) =>
                try
                if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
                const results = await users.findOne(ObjectID(id))
                return results
                catch (e)
                throw e



                // Export garbage as methods on the Users object
                module.exports = createUser, getUsers, findUserById






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 26 '17 at 23:20









                agm1984agm1984

                3,57411733




                3,57411733











                • is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
                  – shanks
                  May 16 '18 at 21:44










                • It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
                  – agm1984
                  May 17 '18 at 22:08
















                • is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
                  – shanks
                  May 16 '18 at 21:44










                • It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
                  – agm1984
                  May 17 '18 at 22:08















                is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
                – shanks
                May 16 '18 at 21:44




                is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
                – shanks
                May 16 '18 at 21:44












                It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
                – agm1984
                May 17 '18 at 22:08




                It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
                – agm1984
                May 17 '18 at 22:08











                5














                go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.



                For example, mongoose is one of the most common. This is what we have in our initial server.js file :



                const mongoose = require('mongoose');
                const options = server: socketOptions: keepAlive: 1;
                mongoose.connect(config.db, options);


                This is everything what is needed to set it up. Now use this anywhere in your code



                const mongoose = require('mongoose');


                And you get that instance you set up with mongoose.connect






                share|improve this answer
















                • 1




                  mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
                  – Saras Arya
                  Apr 13 '17 at 14:16






                • 1




                  Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
                  – agm1984
                  Jul 24 '17 at 6:10















                5














                go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.



                For example, mongoose is one of the most common. This is what we have in our initial server.js file :



                const mongoose = require('mongoose');
                const options = server: socketOptions: keepAlive: 1;
                mongoose.connect(config.db, options);


                This is everything what is needed to set it up. Now use this anywhere in your code



                const mongoose = require('mongoose');


                And you get that instance you set up with mongoose.connect






                share|improve this answer
















                • 1




                  mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
                  – Saras Arya
                  Apr 13 '17 at 14:16






                • 1




                  Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
                  – agm1984
                  Jul 24 '17 at 6:10













                5












                5








                5






                go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.



                For example, mongoose is one of the most common. This is what we have in our initial server.js file :



                const mongoose = require('mongoose');
                const options = server: socketOptions: keepAlive: 1;
                mongoose.connect(config.db, options);


                This is everything what is needed to set it up. Now use this anywhere in your code



                const mongoose = require('mongoose');


                And you get that instance you set up with mongoose.connect






                share|improve this answer












                go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.



                For example, mongoose is one of the most common. This is what we have in our initial server.js file :



                const mongoose = require('mongoose');
                const options = server: socketOptions: keepAlive: 1;
                mongoose.connect(config.db, options);


                This is everything what is needed to set it up. Now use this anywhere in your code



                const mongoose = require('mongoose');


                And you get that instance you set up with mongoose.connect







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jul 13 '16 at 8:46









                libiklibik

                12.1k62859




                12.1k62859







                • 1




                  mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
                  – Saras Arya
                  Apr 13 '17 at 14:16






                • 1




                  Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
                  – agm1984
                  Jul 24 '17 at 6:10












                • 1




                  mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
                  – Saras Arya
                  Apr 13 '17 at 14:16






                • 1




                  Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
                  – agm1984
                  Jul 24 '17 at 6:10







                1




                1




                mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
                – Saras Arya
                Apr 13 '17 at 14:16




                mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
                – Saras Arya
                Apr 13 '17 at 14:16




                1




                1




                Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
                – agm1984
                Jul 24 '17 at 6:10




                Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
                – agm1984
                Jul 24 '17 at 6:10











                2














                Initialize the connection as a promise:



                const MongoClient = require('mongodb').MongoClient
                const uri = 'mongodb://...'
                const client = new MongoClient(uri)
                const connection = client.connect() // initialized connection


                And then call the connection whenever you wish you perform an action on the database:



                 // if I want to insert into the database...
                const connect = connection
                connect.then(() =>
                const doc = id: 3
                const db = client.db('database_name')
                const coll = db.collection('collection_name')
                coll.insertOne(doc, (err, result) =>
                if(err) throw err
                )
                )





                share|improve this answer



























                  2














                  Initialize the connection as a promise:



                  const MongoClient = require('mongodb').MongoClient
                  const uri = 'mongodb://...'
                  const client = new MongoClient(uri)
                  const connection = client.connect() // initialized connection


                  And then call the connection whenever you wish you perform an action on the database:



                   // if I want to insert into the database...
                  const connect = connection
                  connect.then(() =>
                  const doc = id: 3
                  const db = client.db('database_name')
                  const coll = db.collection('collection_name')
                  coll.insertOne(doc, (err, result) =>
                  if(err) throw err
                  )
                  )





                  share|improve this answer

























                    2












                    2








                    2






                    Initialize the connection as a promise:



                    const MongoClient = require('mongodb').MongoClient
                    const uri = 'mongodb://...'
                    const client = new MongoClient(uri)
                    const connection = client.connect() // initialized connection


                    And then call the connection whenever you wish you perform an action on the database:



                     // if I want to insert into the database...
                    const connect = connection
                    connect.then(() =>
                    const doc = id: 3
                    const db = client.db('database_name')
                    const coll = db.collection('collection_name')
                    coll.insertOne(doc, (err, result) =>
                    if(err) throw err
                    )
                    )





                    share|improve this answer














                    Initialize the connection as a promise:



                    const MongoClient = require('mongodb').MongoClient
                    const uri = 'mongodb://...'
                    const client = new MongoClient(uri)
                    const connection = client.connect() // initialized connection


                    And then call the connection whenever you wish you perform an action on the database:



                     // if I want to insert into the database...
                    const connect = connection
                    connect.then(() =>
                    const doc = id: 3
                    const db = client.db('database_name')
                    const coll = db.collection('collection_name')
                    coll.insertOne(doc, (err, result) =>
                    if(err) throw err
                    )
                    )






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Oct 13 '18 at 17:01

























                    answered Oct 13 '18 at 7:54









                    Henry BothinHenry Bothin

                    315




                    315





















                        0














                        A tested solution based on the accepted answer:



                        mongodbutil.js:






                        var MongoClient = require( 'mongodb' ).MongoClient;
                        var _db;
                        module.exports =
                        connectToServer: function( callback )
                        MongoClient.connect( "<connection string>", function( err, client )
                        _db = client.db("<collection name>");
                        return callback( err );
                        );
                        ,
                        getDb: function()
                        return _db;

                        ;





                        app.js:






                        var createError = require('http-errors');
                        var express = require('express');
                        var path = require('path');
                        var cookieParser = require('cookie-parser');
                        var logger = require('morgan');
                        var app = express();
                        app.set('views', path.join(__dirname, 'views'));
                        app.set('view engine', 'ejs');
                        app.use(logger('dev'));
                        app.use(express.json());
                        app.use(express.urlencoded( extended: false ));
                        app.use(cookieParser());
                        app.use(express.static(path.join(__dirname, 'public')));

                        var mongodbutil = require( './mongodbutil' );
                        mongodbutil.connectToServer( function( err )
                        //app goes online once this callback occurs
                        var indexRouter = require('./routes/index');
                        var usersRouter = require('./routes/users');
                        var companiesRouter = require('./routes/companies');
                        var activitiesRouter = require('./routes/activities');
                        var registerRouter = require('./routes/register');
                        app.use('/', indexRouter);
                        app.use('/users', usersRouter);
                        app.use('/companies', companiesRouter);
                        app.use('/activities', activitiesRouter);
                        app.use('/register', registerRouter);
                        // catch 404 and forward to error handler
                        app.use(function(req, res, next)
                        next(createError(404));
                        );
                        // error handler
                        app.use(function(err, req, res, next) );
                        //end of calback
                        );

                        module.exports = app;





                        activities.js -- a route:






                        var express = require('express');
                        var router = express.Router();
                        var mongodbutil = require( '../mongodbutil' );
                        var db = mongodbutil.getDb();

                        router.get('/', (req, res, next) =>
                        db.collection('activities').find().toArray((err, results) =>
                        if (err) return console.log(err)
                        res.render('activities', activities: results, title: "Activities")
                        );
                        );

                        router.post('/', (req, res) =>
                        db.collection('activities').save(req.body, (err, result) =>
                        if (err) return console.log(err)
                        res.redirect('/activities')
                        )
                        );

                        module.exports = router;








                        share|improve this answer

























                          0














                          A tested solution based on the accepted answer:



                          mongodbutil.js:






                          var MongoClient = require( 'mongodb' ).MongoClient;
                          var _db;
                          module.exports =
                          connectToServer: function( callback )
                          MongoClient.connect( "<connection string>", function( err, client )
                          _db = client.db("<collection name>");
                          return callback( err );
                          );
                          ,
                          getDb: function()
                          return _db;

                          ;





                          app.js:






                          var createError = require('http-errors');
                          var express = require('express');
                          var path = require('path');
                          var cookieParser = require('cookie-parser');
                          var logger = require('morgan');
                          var app = express();
                          app.set('views', path.join(__dirname, 'views'));
                          app.set('view engine', 'ejs');
                          app.use(logger('dev'));
                          app.use(express.json());
                          app.use(express.urlencoded( extended: false ));
                          app.use(cookieParser());
                          app.use(express.static(path.join(__dirname, 'public')));

                          var mongodbutil = require( './mongodbutil' );
                          mongodbutil.connectToServer( function( err )
                          //app goes online once this callback occurs
                          var indexRouter = require('./routes/index');
                          var usersRouter = require('./routes/users');
                          var companiesRouter = require('./routes/companies');
                          var activitiesRouter = require('./routes/activities');
                          var registerRouter = require('./routes/register');
                          app.use('/', indexRouter);
                          app.use('/users', usersRouter);
                          app.use('/companies', companiesRouter);
                          app.use('/activities', activitiesRouter);
                          app.use('/register', registerRouter);
                          // catch 404 and forward to error handler
                          app.use(function(req, res, next)
                          next(createError(404));
                          );
                          // error handler
                          app.use(function(err, req, res, next) );
                          //end of calback
                          );

                          module.exports = app;





                          activities.js -- a route:






                          var express = require('express');
                          var router = express.Router();
                          var mongodbutil = require( '../mongodbutil' );
                          var db = mongodbutil.getDb();

                          router.get('/', (req, res, next) =>
                          db.collection('activities').find().toArray((err, results) =>
                          if (err) return console.log(err)
                          res.render('activities', activities: results, title: "Activities")
                          );
                          );

                          router.post('/', (req, res) =>
                          db.collection('activities').save(req.body, (err, result) =>
                          if (err) return console.log(err)
                          res.redirect('/activities')
                          )
                          );

                          module.exports = router;








                          share|improve this answer























                            0












                            0








                            0






                            A tested solution based on the accepted answer:



                            mongodbutil.js:






                            var MongoClient = require( 'mongodb' ).MongoClient;
                            var _db;
                            module.exports =
                            connectToServer: function( callback )
                            MongoClient.connect( "<connection string>", function( err, client )
                            _db = client.db("<collection name>");
                            return callback( err );
                            );
                            ,
                            getDb: function()
                            return _db;

                            ;





                            app.js:






                            var createError = require('http-errors');
                            var express = require('express');
                            var path = require('path');
                            var cookieParser = require('cookie-parser');
                            var logger = require('morgan');
                            var app = express();
                            app.set('views', path.join(__dirname, 'views'));
                            app.set('view engine', 'ejs');
                            app.use(logger('dev'));
                            app.use(express.json());
                            app.use(express.urlencoded( extended: false ));
                            app.use(cookieParser());
                            app.use(express.static(path.join(__dirname, 'public')));

                            var mongodbutil = require( './mongodbutil' );
                            mongodbutil.connectToServer( function( err )
                            //app goes online once this callback occurs
                            var indexRouter = require('./routes/index');
                            var usersRouter = require('./routes/users');
                            var companiesRouter = require('./routes/companies');
                            var activitiesRouter = require('./routes/activities');
                            var registerRouter = require('./routes/register');
                            app.use('/', indexRouter);
                            app.use('/users', usersRouter);
                            app.use('/companies', companiesRouter);
                            app.use('/activities', activitiesRouter);
                            app.use('/register', registerRouter);
                            // catch 404 and forward to error handler
                            app.use(function(req, res, next)
                            next(createError(404));
                            );
                            // error handler
                            app.use(function(err, req, res, next) );
                            //end of calback
                            );

                            module.exports = app;





                            activities.js -- a route:






                            var express = require('express');
                            var router = express.Router();
                            var mongodbutil = require( '../mongodbutil' );
                            var db = mongodbutil.getDb();

                            router.get('/', (req, res, next) =>
                            db.collection('activities').find().toArray((err, results) =>
                            if (err) return console.log(err)
                            res.render('activities', activities: results, title: "Activities")
                            );
                            );

                            router.post('/', (req, res) =>
                            db.collection('activities').save(req.body, (err, result) =>
                            if (err) return console.log(err)
                            res.redirect('/activities')
                            )
                            );

                            module.exports = router;








                            share|improve this answer












                            A tested solution based on the accepted answer:



                            mongodbutil.js:






                            var MongoClient = require( 'mongodb' ).MongoClient;
                            var _db;
                            module.exports =
                            connectToServer: function( callback )
                            MongoClient.connect( "<connection string>", function( err, client )
                            _db = client.db("<collection name>");
                            return callback( err );
                            );
                            ,
                            getDb: function()
                            return _db;

                            ;





                            app.js:






                            var createError = require('http-errors');
                            var express = require('express');
                            var path = require('path');
                            var cookieParser = require('cookie-parser');
                            var logger = require('morgan');
                            var app = express();
                            app.set('views', path.join(__dirname, 'views'));
                            app.set('view engine', 'ejs');
                            app.use(logger('dev'));
                            app.use(express.json());
                            app.use(express.urlencoded( extended: false ));
                            app.use(cookieParser());
                            app.use(express.static(path.join(__dirname, 'public')));

                            var mongodbutil = require( './mongodbutil' );
                            mongodbutil.connectToServer( function( err )
                            //app goes online once this callback occurs
                            var indexRouter = require('./routes/index');
                            var usersRouter = require('./routes/users');
                            var companiesRouter = require('./routes/companies');
                            var activitiesRouter = require('./routes/activities');
                            var registerRouter = require('./routes/register');
                            app.use('/', indexRouter);
                            app.use('/users', usersRouter);
                            app.use('/companies', companiesRouter);
                            app.use('/activities', activitiesRouter);
                            app.use('/register', registerRouter);
                            // catch 404 and forward to error handler
                            app.use(function(req, res, next)
                            next(createError(404));
                            );
                            // error handler
                            app.use(function(err, req, res, next) );
                            //end of calback
                            );

                            module.exports = app;





                            activities.js -- a route:






                            var express = require('express');
                            var router = express.Router();
                            var mongodbutil = require( '../mongodbutil' );
                            var db = mongodbutil.getDb();

                            router.get('/', (req, res, next) =>
                            db.collection('activities').find().toArray((err, results) =>
                            if (err) return console.log(err)
                            res.render('activities', activities: results, title: "Activities")
                            );
                            );

                            router.post('/', (req, res) =>
                            db.collection('activities').save(req.body, (err, result) =>
                            if (err) return console.log(err)
                            res.redirect('/activities')
                            )
                            );

                            module.exports = router;








                            var MongoClient = require( 'mongodb' ).MongoClient;
                            var _db;
                            module.exports =
                            connectToServer: function( callback )
                            MongoClient.connect( "<connection string>", function( err, client )
                            _db = client.db("<collection name>");
                            return callback( err );
                            );
                            ,
                            getDb: function()
                            return _db;

                            ;





                            var MongoClient = require( 'mongodb' ).MongoClient;
                            var _db;
                            module.exports =
                            connectToServer: function( callback )
                            MongoClient.connect( "<connection string>", function( err, client )
                            _db = client.db("<collection name>");
                            return callback( err );
                            );
                            ,
                            getDb: function()
                            return _db;

                            ;





                            var createError = require('http-errors');
                            var express = require('express');
                            var path = require('path');
                            var cookieParser = require('cookie-parser');
                            var logger = require('morgan');
                            var app = express();
                            app.set('views', path.join(__dirname, 'views'));
                            app.set('view engine', 'ejs');
                            app.use(logger('dev'));
                            app.use(express.json());
                            app.use(express.urlencoded( extended: false ));
                            app.use(cookieParser());
                            app.use(express.static(path.join(__dirname, 'public')));

                            var mongodbutil = require( './mongodbutil' );
                            mongodbutil.connectToServer( function( err )
                            //app goes online once this callback occurs
                            var indexRouter = require('./routes/index');
                            var usersRouter = require('./routes/users');
                            var companiesRouter = require('./routes/companies');
                            var activitiesRouter = require('./routes/activities');
                            var registerRouter = require('./routes/register');
                            app.use('/', indexRouter);
                            app.use('/users', usersRouter);
                            app.use('/companies', companiesRouter);
                            app.use('/activities', activitiesRouter);
                            app.use('/register', registerRouter);
                            // catch 404 and forward to error handler
                            app.use(function(req, res, next)
                            next(createError(404));
                            );
                            // error handler
                            app.use(function(err, req, res, next) );
                            //end of calback
                            );

                            module.exports = app;





                            var createError = require('http-errors');
                            var express = require('express');
                            var path = require('path');
                            var cookieParser = require('cookie-parser');
                            var logger = require('morgan');
                            var app = express();
                            app.set('views', path.join(__dirname, 'views'));
                            app.set('view engine', 'ejs');
                            app.use(logger('dev'));
                            app.use(express.json());
                            app.use(express.urlencoded( extended: false ));
                            app.use(cookieParser());
                            app.use(express.static(path.join(__dirname, 'public')));

                            var mongodbutil = require( './mongodbutil' );
                            mongodbutil.connectToServer( function( err )
                            //app goes online once this callback occurs
                            var indexRouter = require('./routes/index');
                            var usersRouter = require('./routes/users');
                            var companiesRouter = require('./routes/companies');
                            var activitiesRouter = require('./routes/activities');
                            var registerRouter = require('./routes/register');
                            app.use('/', indexRouter);
                            app.use('/users', usersRouter);
                            app.use('/companies', companiesRouter);
                            app.use('/activities', activitiesRouter);
                            app.use('/register', registerRouter);
                            // catch 404 and forward to error handler
                            app.use(function(req, res, next)
                            next(createError(404));
                            );
                            // error handler
                            app.use(function(err, req, res, next) );
                            //end of calback
                            );

                            module.exports = app;





                            var express = require('express');
                            var router = express.Router();
                            var mongodbutil = require( '../mongodbutil' );
                            var db = mongodbutil.getDb();

                            router.get('/', (req, res, next) =>
                            db.collection('activities').find().toArray((err, results) =>
                            if (err) return console.log(err)
                            res.render('activities', activities: results, title: "Activities")
                            );
                            );

                            router.post('/', (req, res) =>
                            db.collection('activities').save(req.body, (err, result) =>
                            if (err) return console.log(err)
                            res.redirect('/activities')
                            )
                            );

                            module.exports = router;





                            var express = require('express');
                            var router = express.Router();
                            var mongodbutil = require( '../mongodbutil' );
                            var db = mongodbutil.getDb();

                            router.get('/', (req, res, next) =>
                            db.collection('activities').find().toArray((err, results) =>
                            if (err) return console.log(err)
                            res.render('activities', activities: results, title: "Activities")
                            );
                            );

                            router.post('/', (req, res) =>
                            db.collection('activities').save(req.body, (err, result) =>
                            if (err) return console.log(err)
                            res.redirect('/activities')
                            )
                            );

                            module.exports = router;






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 30 '18 at 10:49









                            stevesteve

                            664




                            664



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24621940%2fhow-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Barbados

                                How to read a connectionString WITH PROVIDER in .NET Core?

                                Node.js Script on GitHub Pages or Amazon S3