How to reuse mongodb connection in node.js

前端 未结 2 1968
清酒与你
清酒与你 2020-12-10 08:02

I\'m using node-mongodb-native driver with mongodb to write a website.

I have a question about how to open mongodb connection once, then use it in collection name us

2条回答
  •  北海茫月
    2020-12-10 08:11

    You can connect once, and then reuse it as many times as you want:

    var mongodb = require('mongodb');
    var events = require('events');
    var event = new events.EventEmitter();
    var access = new mongodb.Server(host, port, { });
    var client = null;
    
    new mongodb.Db('YOUR DATABASE', access, { safe: true, auto_reconnect: true }).open(function (err, c) {
      if (!err) {
        client = c;
        console.log('database connected');
        event.emit('connect');
      } else {
        console.log('database connection error', err);
        event.emit('error');
      }
    });
    
    exports.get = function(fn) {
      if(client) {
        fn(client);
      } else {
        event.on('connect', function() {
          fn(client);
        });
      }
    };
    

    And then reuse it:

    var db = require('./db');
    var items;
    db.get(function(client) {
      items = new mongodb.Collection(client, 'collection');
    });
    
    // then anywhere in your code
    db.get(function() {
      // items.find({ ...
    });
    

提交回复
热议问题