保持MongoDB数据库连接

时间:2022-06-01 21:07:26

In so many introductory examples of using MongoDB, you see code like this:

在许多使用MongoDB的介绍性示例中,您会看到如下代码:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db)
{
    /* Some operation... CRUD, etc. */
    db.close();
});

If MongoDB is like any other database system, open and close operations are typically expensive time-wise.

如果MongoDB像任何其他数据库系统一样,那么打开和关闭操作通常都需要花费大量的时间。

So, my question is this: Is it OK to simply do the MongoClient.connect("... once, assign the returned db value to some module global, have various functions in the module do various database-related work (insert documents into collections, update documents, etc. etc.) when they're called by other parts of the application (and thereby re-use that db value), and then, when the application is done, only then do the close.

所以,我的问题是:简单地做mongoclient可以吗?一次,返回的分贝值分配给全球一些模块,有各种功能模块做各种数据库相关工作(插入文档收集、更新文件,等等)。当他们被应用程序的其他部分(分贝值,从而重用),然后,当应用程序完成,只有这样做。

In other words, open and close are done once - not every time you need to go and do some database-related operation. And you keep re-using that db object that was returned during the initial open\connect, only to dispose of it at the end, with the close, when you're actually done with all your database-related work.

换句话说,打开和关闭只执行一次——而不是每次需要执行与数据库相关的操作时。你继续重用在初始打开\连接期间返回的db对象,只在结束时处理它,当你完成所有与数据库相关的工作时。

Obviously, since all the I/O is asynch, before the close you'd make sure that the last database operation completed before issuing the close. Seems like this should be OK, but i wanted to double-check just in case I'm missing something as I'm new to MongoDB. Thanks!

显然,由于所有的I/O都是异步的,在关闭之前,您应该确保最后一个数据库操作在发出关闭之前完成。看起来这应该没问题,但我想再检查一下,以防漏掉什么,因为我是MongoDB的新手。谢谢!

1 个解决方案

#1


40  

Yes, that is fine and typical behavior. start your app, connect to db, do operations against the db for a long time, maybe re-connect if the connection ever dies unexpectedly, and then just never close the connection (just rely on the automatic close that happens when your process dies).

是的,这是很好的典型行为。启动您的应用程序,连接到db,对db进行长时间的操作,如果连接意外终止,可能重新连接,然后永远不要关闭连接(仅依赖于进程终止时发生的自动关闭)。

#1


40  

Yes, that is fine and typical behavior. start your app, connect to db, do operations against the db for a long time, maybe re-connect if the connection ever dies unexpectedly, and then just never close the connection (just rely on the automatic close that happens when your process dies).

是的,这是很好的典型行为。启动您的应用程序,连接到db,对db进行长时间的操作,如果连接意外终止,可能重新连接,然后永远不要关闭连接(仅依赖于进程终止时发生的自动关闭)。