Es ist in Ordnung, die gleiche Verbindung zu verwenden, um alle Ihre Anfragen auszuführen. Denken Sie daran, dass der Mongo Driver für Node.js asynchron ist. Das bedeutet, dass es die Abfragen an den mongod-Server sendet und mit der Ausführung Ihres Codes fortfährt, ohne auf die Ergebnisse zu warten. Wenn der Server jedoch mit den Abfrageergebnissen antwortet, ruft der Mongo-Treiber Ihre Rückruffunktion auf. Daher liegt die gesamte Arbeitslast auf dem mongod-Server und nicht auf Ihrer Knoten-App.
Überprüfen Sie dieses Skript, das dies beweist. Sie können sehen, dass alles asynchron ausgeführt wird und die Knoten-App den Ausführungsablauf fortsetzen kann.
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)
});
Dies ist die Ausgabe nach diesem Knoten Programm ausgeführt wird:
$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