2011-03-27 72 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 
    } 
    } 

或者你可以使用一些簡化這些操作模塊(貓鼬,蒙古......)