简体   繁体   中英

Persisting mongodb (2.0) connection through nodejs Express Application

I'm having some trouble with a presumably simple task. I'm starting an express (4) application with the native mongodb (2) driver and looking into how to open a connection to the mongo server/db once, re-use it through the express lifetime, and close it when the express application closes.

Here's what I have so far (only showing the pertinent snippets):

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

Mongodb does not have built in support for persistent connections. I would recommend looking into Mongoose . While Mongoose does not have persistent connections it has connection pools. Which means instead of reconnecting mongodb on each request it takes one connection from the pool of reusable connections and then returns it back.As per your example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM