2011-03-27 94 views
1

现在我在每次请求打开一个馆藏:node-mongodb-native保存集合?

即:

app.get('/route', function (req, res) { 
    db.collection('user', function (err, collection) { 
     collection.find(blah) // do something 

    app.get('/route2', function (req, res) { 
    db.collection('user', function (err, collection) { 
     collection.find(foo) // do something 

    app.get('/route3', function (req, res) { 
    db.collection('user', function (err, collection) { 
     collection.find(bar) // do something 

那是不正确的?我想我应该将'用户'集合保存到变量中,而不是每次请求都获取它。

谢谢。

回答

2

你可以有一个变量collection并使用它:

db.collection('user', function (err, collection) { 
    app.get('/route', function (req, res) { 
     collection.find(blah) // do something 
    } 
    app.get('/route2', function (req, res) { 
     collection.find(foo) // do something 
    } 
    app.get('/route3', function (req, res) { 
     collection.find(bar) // do something 
    } 
    } 

或者你可以使用一些简化这些操作模块(猫鼬,蒙古......)