2017-02-27 2 views
0

私はノードベースのプロジェクトでMongoDBデータベースへの単一接続を使用しています。まず、 "db"変数を宣言し、その単一の変数または接続に対してすべてのデータベース関連のCRUD操作を実行します。Mongodbへの1回の接続でデータベースにアクションを実行することをお勧めしますか?

複数の接続を作成することをお勧めしますか?何が結果になるでしょうか?続き

はラフな構造です:

var db; 
MongoClient.connect(url, (err, database) => { 
    db = database; 
    one(db) 
}) 

function one(db) { 
    // doing something with db 
    two(db) 
} 

function two(db) { 
    // doing something with db 
    three(db) 
    five(db) 
    six(db) 
} 

function three(db) { 
    // doing something with db 
    four(db) 
    seven(db) 
} 

など....

答えて

1

あなたのクエリのすべてを実行するために同じ接続を使用して大丈夫です。 Node.jsのMongoドライバは非同期であることに注意してください。つまり、クエリをmongodサーバーに送信し、結果を待たずにコードの実行を続けます。しかし、サーバがクエリ結果で応答すると、Mongoドライバはコールバック関数を呼び出します。したがって、重いワークロードはすべてあなたのノードアプリケーションにないmongodサーバーにあります。

これを証明するこのスクリプトをチェックしてください。すべてが非同期で実行され、ノードアプリケーションは実行の流れを続けることができます。

var MongoClient = require('mongodb').MongoClient 

function testDb(db) { 
    var documents = [] 
    for(var i = 0; i < 100000; i++) 
     documents.push({test: 'just testing', exp: [1,2,3]}) 

    var col = db.collection('cart') 

    console.log('insert the 1st one!') 

    col.insertMany(documents, {w:1, j:1}, function(err, results) { 
     console.log('we inserted the 1st documents') 
    }) 

    console.log('fetch the 2nd one!') 

    col.find({}).toArray(function(err, results) { 
     console.log('we got the 2nd result' || err) 
    }) 

    console.log('fetch the 3rd one!') 

    col.find({}).toArray(function(err, results) { 
     console.log('we got the 3rd results' || err) 
    }) 

    console.log('fetch the 4th one!') 

    col.find({}).toArray(function(err, results) { 
     console.log('we got the 4th results' || err) 
    }) 

    console.log('No more fetches or inserts!') 
    console.log('-----------------------------------------') 
    console.log('Starting to do some other work!') 
    console.log('-----------------------------------------') 

    var t = [] 
    for(var i = 0; i < 100000; i++) 
     t.push(i) 

    console.log('-----------------------------------------') 
    console.log('Done with the extra work!') 
    console.log('-----------------------------------------') 
} 

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { 
    testDb(db) 
}); 

これは、そのノードのプログラムを実行した後に出力されます。

$bash node test.js 
insert the 1st one! 
fetch the 2nd one! 
fetch the 3rd one! 
fetch the 4th one! 
No more fetches or inserts! 
----------------------------------------- 
Starting to do some other work! 
----------------------------------------- 
----------------------------------------- 
Done with the extra work! 
----------------------------------------- 
we got the 4th results 
we got the 3rd results 
we got the 2nd result 
we inserted the 1st documents 
関連する問題