这是好的使用相同的连接来执行所有的查询。请记住,Node.js的Mongo Driver是异步的。这意味着它会将查询发送到mongod服务器,并继续执行代码而无需等待结果。但是,当服务器响应查询结果时,Mongo Driver将调用您的回调函数。因此,所有繁重的工作负载都在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