2017-02-27 42 views
0

我只在基于Node的项目中使用MongoDB数据库的单一连接。首先,声明一个“db”变量,然后在该变量或连接上执行所有数据库相关的CRUD操作。使用Mongodb的单一连接对数据库执行操作是否是一种很好的做法?

这是一个很好的做法,或者我需要创建多个连接?会有什么后果?

下面是一个粗略的结构:

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 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 
相关问题