gpt4 book ai didi

node.js - 如何在 Node.js 中正确关闭 MongoDB 连接?

转载 作者:行者123 更新时间:2023-12-03 00:44:09 24 4
gpt4 key购买 nike

以下代码“有效”,因为它在控制台中返回文档:

var Db = require('mongodb').Db;
var mongoUri = 'mongodb://localhost:27017/basketball';

exports.games = function(req, res){
console.log(req);
res.end("list of games");
Db.connect(mongoUri, function(err, db) {
console.log('connected!');
db.collection('game_ids', function(err, coll) {
coll.findOne({'date' : '2012-12-07'}, function(err, doc) {
console.log(doc);
});
});
db.close();
});
};

>
connected!
{ _id: 50b01b31597f14213a00010f,
date: '2012-12-07',
espn_id: '400277990',
hid: '20',
aid: '2',
home: '76ers',
away: 'Celtics',
season: '2013',
during: 'regular',
scrape: null }

但是当我查看 mongod 控制台时,我发现每次刷新页面时,似乎都会打开越来越多的连接,而不会关闭它们。在这里你可以看到,经过 5 次刷新后,我现在显然有 25 个打开的连接(你必须滚动到右侧才能看到数字):

Sat Dec  8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57587 #121 (21 connections now open)
Sat Dec 8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57588 #122 (22 connections now open)
Sat Dec 8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57589 #123 (23 connections now open)
Sat Dec 8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57590 #124 (24 connections now open)
Sat Dec 8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57591 #125 (25 connections now open)

我做错了什么?

最佳答案

您正在尝试在工作完成时关闭连接。

    // the work is done in the call back functions
db.collection('game_ids', function(err, coll) {
coll.findOne({'date' : '2012-12-07'}, function(err, doc) {
console.log(doc);
});
});

// the work above with the callback is async, this executes
// immediately after initiating that work.
db.close();

如果您要在每次调用中打开和关闭,那么您将在工作完成后关闭(在您的情况下是在 console.log 调用之后)。

您可能还想研究连接池,这样您就不必在每次调用时打开/关闭。更多内容请参见:

http://technosophos.com/content/nodejs-connection-pools-and-mongodb

您还应该通过检查回调函数中的错误来进行错误检查。例如,如果获取集合失败,则不应执行 findOne 等...

关于node.js - 如何在 Node.js 中正确关闭 MongoDB 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13781658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com