在Express路由器中使用mongoDB [英] Using mongoDB in Express routers

查看:150
本文介绍了在Express路由器中使用mongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用node / express和mongodb,而且我有点混淆连接工作。

I am just learning how to use node/express and mongodb, and I am a little confused about pooling connections works.

我现在的策略是在路由器级别拥有数据库连接,因此每个路由都有自己的连接。我的一条路线的代码如下所示:

My strategy right now is to have the database connections at the router level, so each route has its own connection. My code for one of my routes looks like this:

var express = require('express');
var router = express.Router();

var config = require('../config.json');

var url = config.db.URI;

var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

var db;

// Connect to database
router.all('*', function(req, res, next) {
    console.log('Connecting to db');
    MongoClient.connect(url, function(err, database) {
        assert.equal(null, err);
        db = database;
    });
    next();
});

// GET admin list page
router.get('/', function(req, res, next) {
    res.render('lists/index');
    var coll = db.collection('lists');
    coll.find().each(function(err, obj) {
        console.log(obj);
    });
    next();
});

router.get('/new', function(req, res, next) {
    res.render('lists/new');
    next();
});

router.all('*', function(req, res, next) {
    console.log('Closing database');
    //db.close();
});

module.exports = router;

我正在测试这个视图与我的数据库的交互方式,包括我的http请求的两个router.all函数。在我看来,任何时候都要求这个路由器中的一个页面,服务器应该连接到数据库,允许相应的http请求函数来访问数据库(在这种情况下只是将其内容打印到控制台),然后在最后关闭它一旦http请求完成。然而,这种情况并非如此。正如你可以看到的,我已经注释掉了db.close函数,因为它抛出一个错误,说发送后不能设置头文件。我认为这意味着我不太明白快速路线管道,事情并不按照我期望的顺序执行。

I am testing how this view interacts with my database with the two router.all functions wrapping my http requests. In my mind, any time a page in this router is requested, the server should connect to the database, allow the corresponding http request function to access the database (in this case just printing its contents to console), then close it at then end once the http request is done. However, this is not the case. As you can see I've commented out the db.close function as it throws an error saying "Can't set headers once they are sent" with it. I assume this means that I don't quite understand the Express route "pipeline" and things are not executing in the order I expect them too.

是否有不同的路由器方法我应该使用?也许路由器?或者我以错误的方式接近这个,我应该把数据库连接到别的地方吗?

Is there a different router method I should be using? Maybe router.use? Or am I approaching this in the wrong way, should I put my database connection somewhere else?

我正在使用这个,作为一个参考,有什么好的做法,只要pooling去,但他们似乎关闭连接?如果我没有关闭连接,我只看到我的mongodb连接数上升了,我不认为是一件好事。只是你必须在连接的数量和长度之间找到平衡?

I am using this as a reference somewhat on what is good practice as far as pooling goes, but they don't seem to close the connection? If I don't close the connection I just see my number of mongodb connections go up and up, which I don't think is a good thing. Is it just that you have to find a balance between the number and length of connections?

推荐答案

你应该连接一次,在所有处理程序中使用它。

You should make your connection once and use it in all handlers.

现在您正在做的是在每个请求上重新连接到数据库,即使是那些不使用数据库的请求所有。此外,在等待连接建立之前,您打电话给next()。

Right now what you're doing is reconnecting to the database on every single request, even on those requests that don't use the database at all. Besides, you're calling next() before even waiting for the connection to get established.

数据库连接是持久的 - 不是一次性的事情,所以你你的方法很可能会获得很差的表现,我甚至不确定你为什么要这样做。单个连接是否有任何问题?我不认为这样锤击您的数据库将有所帮助。如果有的话,只能使事情变得更糟。

Database connections are meant to be persistent - not one-time things, so you're likely to get very poor performance with your approach and I'm not even sure why would you want to do that. Did you have any problems with a single connection? I don't think that hammering your database like that would help. If anything, it can only make things worse.

当您使用本机
MongoDB Node.js驱动程序有一些您可以使用的选项,如:

When you connect to Mongo with the native MongoDB Node.js Driver there are some options that you can use, like:


  • poolSize - 设置每个服务器或代理连接的最大poolSize(默认为 5

  • autoReconnect - 重新连接错误(默认为 true

  • poolSize - Set the maximum poolSize for each individual server or proxy connection (default is 5)
  • autoReconnect - Reconnect on error (default is true)

其他一些有趣的选项是: reconnectTries reconnectInterval keepAlive connectTimeoutMS socketTimeoutMS

Some other interesting options are: reconnectTries, reconnectInterval, keepAlive, connectTimeoutMS, socketTimeoutMS.

如果您对默认值不满意,可以更改这些选项的值。

You can change the values of those options if you're not happy with the defaults.

有关详细信息,请参阅:

For more info see:

  • Connection Failures and Retries
  • MongoClient or how to connect in a new and better way
  • Tutorials / Connect to MongoDB
  • Reference / Connection Options / Connection Settings
  • Question about node.js mongo driver auto-reconnect (mailing list)

这篇关于在Express路由器中使用mongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆