我在推測一個簡單的任務時遇到了一些麻煩。我使用本地mongodb(2)驅動程序啓動express(4)應用程序,並研究如何打開與mongo server/db的連接一次,在express生命週期中重新使用它,並在快速應用程序關閉。通過nodejs Express應用程序持續的mongodb(2.0)連接
這裏是我到目前爲止(只顯示相關的片段):
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/course';
// This cannot be the correct way to do this.
// dbClient doesn't seem to be persisting the connection
// details when connect(...) returns;
var dbClient;
MongoClient.connect(url, {native_parser: true}, function(err,db) {
if(err) throw err;
dbClient = db
});
app.get('/', function(req, res) {
// 1) How do I access the MongoDB connection at this point?
// Need a way to persist the connection and access it here.
// 2) How exaclty would I query a specific document here?
// Should I be working with MongoDB 'collections'
// and use that to find documents?
dbClient.find({}, function(err, doc) {
console.log(doc);
res.render('index', doc);
});
});
app.listen(8000);
console.log("Listening at http://localhost:8000");
是,使用MongClient,你就必須選擇集合首先在你嘗試找到某物之前。 https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html –
至於堅持連接,我不知道這是一個好主意或不。這將取決於連接是否一次處理多個請求,或者它是否像大多數其他數據庫系統一樣只處理一個請求。 –