3

Node.JS を使用して単純な Web アプリを作成していて、mongoDB をメインのデータ ストレージとして使用したいと考えています。
Node-mongodb-native ドライバーでは、実際にデータをクエリまたは保存する (DB 接続を開き、認証し、コレクションを取得する) 前に、連鎖呼び出しを行う必要があります。
アプリケーションを初期化するとき、この初期化を行うのに最適な場所はどこですか?各リクエストハンドラー内またはグローバル?

4

1 に答える 1

2

Mongo の初期化をリクエスト ハンドラーの外に置く方がはるかに優れています。そうしないと、提供されるすべてのページに再接続されます。

var mongo = require('mongodb');

// our express (or any HTTP server)
var app = express.createServer();

// this variable will be used to hold the collection for use below
var mongoCollection = null;

// 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 Db('testdb', server);
db.open(function(error, databaseConnection){
    databaseConnection.createCollection('testCollection', function(error, collection) {

      if(!error){
        mongoCollection = collection;
      }

      // now we have a connection - tell the express to start
      app.listen(80);

    });
});

app.use('/', function(req, res, next){
    // here we can use the mongoCollection - it is already connected
    // and will not-reconnect for each request (bad!)
})
于 2012-08-16T11:07:09.223 に答える