我使用的是express框架,希望在不使用mongose的情况下连接到mongodb,但使用本地nodejs mongodb驱动程序。如果每次都不创建新的连接,我怎么能做到这一点?
为了处理获取或发布请求,我目前为每个请求打开一个到数据库的新连接,并在请求完成后关闭它。有更好的方法吗?提前谢谢。
按照我评论中的示例进行修改,以便应用程序处理错误,而不是启动服务器失败。
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var dbURL = "mongodb://localhost:27017/integration_test";
var db;
// Initialize connection once
MongoClient.connect(dbURL, function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here
// because most apps *should* fail to start if they have no DB.
// If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
app.get("/", function(req, res, next) {
var collection = "replicaset_mongo_client_collection";
db.collection(collection).find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});
app.use(function(err, req, res){
// handle error here. For example, logging and
// returning a friendly error page
});
// Starting the app here will work, but some users
// will get errors if the db connection process is slow.
app.listen(3000);
console.log("Listening on port 3000");
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/dbname';
module.exports = function(callback) {
mongodb.MongoClient.connect(uri, callback);
};
将这个片段放在一个文件中,比如connect.js,然后在您为http请求声明函数的文件中需要这个文件(connect.js)。