持续打开MongoDB数据库连接 [英] Keeping open a MongoDB database connection
问题描述
在使用MongoDB的许多入门示例中,您将看到类似以下的代码:
In so many introductory examples of using MongoDB, you see code like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db)
{
/* Some operation... CRUD, etc. */
db.close();
});
如果MongoDB与其他任何数据库系统一样,open
和close
操作通常在时间上很昂贵.
If MongoDB is like any other database system, open
and close
operations are typically expensive time-wise.
所以,我的问题是:只需简单地执行一次MongoClient.connect("...
,将返回的db
值分配给全局某个模块,就可以了,模块中的各种功能可以完成各种与数据库相关的工作(将文档插入到集合,更新文档等),然后由应用程序的其他部分调用它们(从而重新使用该db
值),然后在应用程序完成后才执行close
.
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
.
换句话说,open
和close
仅执行一次-并非每次您都需要进行一些与数据库相关的操作时.而且,当实际完成所有与数据库有关的工作时,您将继续使用在最初的open\connect
中返回的db
对象,直到最后将其与close
一起使用.
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.
很明显,由于所有I/O都是异步的,因此在发布close
之前,您要确保最后一个数据库操作已完成.似乎这样应该可以,但我想仔细检查一下,以防万一我刚接触MongoDB时遗漏了一些东西.谢谢!
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!
推荐答案
是的,这是正常的行为.启动您的应用程序,连接到数据库,对数据库进行长时间的操作,如果连接意外中断,则可能重新连接,然后再也不要关闭连接(仅依赖于进程终止时发生的自动关闭)
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).
这篇关于持续打开MongoDB数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!