Node.js and MongoDB, reusing the DB object

前端 未结 2 1208
温柔的废话
温柔的废话 2020-12-23 10:35

I\'m new to both Node.js and MongoDB, but I\'ve managed to put some parts together from SO and the documentation for mongo.

Mongo documentetion gives the example:

相关标签:
2条回答
  • 2020-12-23 11:22

    From your last code snippet, seems like you using Express or similar framework. You can use express-mongo-db to get connection inside req object. This middleware will cache connection for you and share it with other incoming requests:

    app.use(require('express-mongo-db')(require('mongodb'), { db: 'test' }))
    app.post('/employee', function(req, res){
        // req.db.collection('names'),insert(req.name)
        // Put req.name in database
    });
    
    
    app.post('/car', function(req, res){
        // req.db.collection('names').insert(req.name)
        // Put req.car in database
    });
    
    0 讨论(0)
  • 2020-12-23 11:25

    You could always write a module which initializes your database connections, and makes them accessible throughout your program. For example:

    mongo.js

    var mongodb = require('mongodb');
    
    module.exports.init = function (callback) {
      var server = new mongodb.Server("127.0.0.1", 27017, {});
      new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
        //export the client and maybe some collections as a shortcut
        module.exports.client = client;
        module.exports.myCollection = new mongodb.Collection(client, 'myCollection');
        callback(error);
      });
    };
    

    app.js

    var mongo = require('./mongo.js');
    
    //setup express...
    
    //initialize the db connection
    mongo.init(function (error) {
        if (error)
            throw error;
    
        app.listen(80); //database is initialized, ready to listen for connections
    });
    

    randomFile.js

    var mongo = require('./mongo.js');
    
    module.exports.doInsert = function () {
      //use the collection object exported by mongo.js
      mongo.myCollection.insert({test: 'obj'}, {safe:true}, function(err, objects) {
        if (err)
            console.warn(err.message);
      });
    };
    

    I know people talk about pooling, but when I did benchmarking of pooling mongo connections vs. a single connection for all requests, the single connection actually performed better. Granted, this was about a year ago, but I doubt that basic concept has changed. All the requests are asynchronous, so it's not like multiple connections are necessary in order to make simultaneous requests.

    As far as MongoClient, I guess that's the new syntax they're encouraging. Either way, it's essentially a client object that you want to keep and make accessible regardless of which style you use.

    0 讨论(0)
提交回复
热议问题