如何在Node.js Web应用程序中管理MongoDB连接? [英] How do I manage MongoDB connections in a Node.js web application?

查看:141
本文介绍了如何在Node.js Web应用程序中管理MongoDB连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 node-mongodb-native 驱动程序与MongoDB写入

I'm using the node-mongodb-native driver with MongoDB to write a website.

我有一些关于如何管理连接的问题:

I have some questions about how to manage connections:


  1. 对于所有请求,只使用一个MongoDB连接就够了吗?有任何性能问题吗?

  1. Is it enough using only one MongoDB connection for all requests? Are there any performance issues? If not, can I setup a global connection to use in the whole application?

如果没有,如果我在请求到达时打开一个新的连接,并在处理请求时关闭它?打开和关闭连接是否昂贵?

If not, is it good if I open a new connection when request arrives, and close it when handled the request? Is it expensive to open and close a connection?

我应该使用全局连接池吗?我听到驱动程序有一个本机连接池。这是个不错的选择吗?

Should I use a global connection pool? I hear the driver has a native connection pool. Is it a good choice?

如果我使用连接池,应该使用多少个连接?

If I use a connection pool, how many connections should be used?

还有其他事情我应该注意吗?

Are there other things I should notice?


推荐答案

node-mongodb-native的主要提交者说


当您的应用程序启动并重用
db对象时,您打开一次MongoClient.connect。它不是一个单独的连接池每个.connect
创建一个新的连接池。

You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.

重用由MongoClient.connect()产生的db对象。这给你池,并将提供明显的速度增加与打开/关闭连接每个数据库操作相比。

So, to answer your question directly, reuse the db object that results from MongoClient.connect(). This gives you pooling, and will provide a noticeable speed increase as compared with opening/closing connections on each db action.

这篇关于如何在Node.js Web应用程序中管理MongoDB连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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