简体   繁体   English

关闭mongodb连接

[英]Closing mongodb connections

I use native mongodb driver with Expressjs, I don't want to open and close connections on a regular basis in my routes. 我将本机mongodb驱动程序与Expressjs一起使用,我不想在路由中定期打开和关闭连接。 I want to open once use one connection in all my next() functions and then close when done. 我想在所有next()函数中使用一个连接打开一次,然后在完成后关闭。

I saw that after opening a connection I can pass the db object to next() functions in request object and use it. 我看到打开连接后,我可以将db对象传递给请求对象中的next()函数并使用它。

When I try to close the connection like var db=req.db; 当我尝试关闭类似var db = req.db的连接时; db.close(); db.close(); it throws an error. 它抛出一个错误。

Inorder to solve this issue I have decided to use settimeout function to close my connection. 为了解决此问题,我决定使用settimeout函数关闭我的连接。

I can pass around and use the db obj and send response and the after 1-2 seconds db obj is closed by settimeout. 我可以绕过并使用db obj并发送响应,并且1-2秒后db obj被settimeout关闭。

I'm worried if the requests are more will the settimeout functions effect the servers performance. 我担心如果请求更多,则settimeout函数会影响服务器性能。 If I use this trick to manage my db connections. 如果我使用此技巧来管理我的数据库连接。

Sorry, I forgot to do: 抱歉,我忘了做:

db=client.db('test')

and: 和:

db.close();

Change in later versions can't directly open db without getting the client, using native mongodb-nodejs driver. 更高版本中的更改无法使用本机mongodb-nodejs驱动程序在没有获取客户端的情况下直接打开db。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM