簡體   English   中英

通過Node.js Express應用程序保持mongodb(2.0)連接

[英]Persisting mongodb (2.0) connection through nodejs Express Application

我在執行簡單的任務時遇到了麻煩。 我正在使用本機mongodb(2)驅動程序啟動一個express(4)應用程序,並研究如何一次打開與mongo服務器/ db的連接,在Express生命周期內重用它,並在Express應用程序關閉時關閉它關閉。

這是我到目前為止的內容(僅顯示相關片段):

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沒有內置的持久連接支持。 我建議研究貓鼬 雖然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);
});
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM