节点mongodb本地保持收集?

现在我正在打开每个请求的集合:

即:

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 

这是不正确的? 我想我应该把'用户'集合保存到一个variables,并没有得到它的每一个请求。

谢谢。

你可以有一个variablescollection并使用它:

  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 } } 

或者你可以使用一些简化这些操作的模块(Mongoose,蒙古…)