NodeJS-MongoDB:使用开放连接 [英] NodeJS - MongoDB: use an opening connection

查看:61
本文介绍了NodeJS-MongoDB:使用开放连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好建立一个新的连接或重新使用?使用模块时,因为我习惯于将代码分成几个文件.

It is better to open a new connection or re-use ? when using module, because I'm used to separate my code into several files.

a.js

module.exports = function (req, res) {

  new mongodb.... (err, db) { // open a connection
    b(function (err, result) {
      db.close(); // close the connection
      res.send(result);
    });
  });

};

b.js

// re-open a connection ? or take the connection of "a.js" ? (passing "db")

异步时,必须小心继续使用相同的连接(套接字).这样可以确保直到写入完成后才能开始下一个操作.

When asynchronous, one must be careful to continue using the same connection (socket). This ensures that the next operation will not begin until after the write completes.

谢谢!

推荐答案

当您require('somemodule')然后再次要求它时,它将使用ALREADY加载的实例.这使您可以轻松创建单例.

When you require('somemodule') and then require it again a second time, it will use the ALREADY loaded instance. This lets you create singletons quite easily.

所以-在sharedmongo.js内部:

var mongo = require('mongodb');

// this variable will be used to hold the singleton connection
var mongoCollection = null;

var getMongoConnection = function(readyCallback) {

  if (mongoCollection) {
    readyCallback(null, mongoCollection);
    return;
  }

  // get the connection
  var server = new mongo.Server('127.0.0.1', 27017, {
    auto_reconnect: true
  });

  // get a handle on the database
  var db = new mongo.Db('squares', server);
  db.open(function(error, databaseConnection) {
    databaseConnection.createCollection('testCollection', function(error, collection) {

      if (!error) {
        mongoCollection = collection;
      }

      // now we have a connection
      if (readyCallback) readyCallback(error, mongoCollection);
    });
  });
};
module.exports = getMongoConnection;

然后在a.js内部:

var getMongoConnection = require('./sharedmongo.js');
var b = require('./b.js');
module.exports = function (req, res) {
  getMongoConnection(function(error, connection){
    // you can use the Mongo connection inside of a here
    // pass control to b - you don't need to pass the mongo
    b(req, res);
  })
}

b.js内部:

var getMongoConnection = require('./sharedmongo.js');
module.exports = function (req, res) {
  getMongoConnection(function(error, connection){
    // do something else here
  })
}

这个想法是当a.jsb.js都调用getMongoCollection时,它第一次连接,第二次返回已经连接的.这样可以确保您使用相同的连接(套接字).

The idea is when both a.js and b.js call getMongoCollection, the first time it will connect, and the second time it will return the already connected one. This way it ensure you are using the same connection (socket).

这篇关于NodeJS-MongoDB:使用开放连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆