通过nodejs Express Application保持mongodb(2.0)连接

时间:2015-05-27 20:24:57

标签: javascript node.js mongodb express

我在完成一项简单的任务时遇到了一些麻烦。我正在使用本机mongodb(2)驱动程序启动express(4)应用程序,并研究如何打开与mongo server / db的连接一次,在明确的生命周期内重新使用它,并在关闭时关闭它快递申请结束。

这是我到目前为止所做的事情(仅显示相关的片段):

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");

1 个答案:

答案 0 :(得分:1)

Mongodb没有内置的持久连接支持。我建议调查一下Mongoose。虽然Mongoose没有持久连接,但它有连接池。这意味着不是在每个请求上重新连接mongodb,而是从可重用连接池中获取一个连接,然后将其返回。根据您的示例:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/');
var myModel = mongoose.model('course');

app.get('/', function(req, res) {
     myModel.find({}, function(err, doc) {
     console.log(doc);
     res.render('index', doc);
});
});