node.js - 将 MongoDB 与本机驱动程序和 Express.js 一起使用时,“拓扑被破坏”
问题描述
我已经实现了从 MongoDB 获取数据的简单应用程序
const express = require('express')
const app = express()
const port = 3000
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbConnectionURL = 'mongodb://localhost:27017';
const dbName = 'todo';
const dbClient = new MongoClient(dbConnectionURL);
function findTodos(db, callback) {
const collection = db.collection('todos');
collection.find({}).toArray(function (err, todos) {
assert.equal(err, null);
console.log("Found the following records");
console.log(todos)
callback(todos);
});
}
app.get('/', (req, res) => {
dbClient.connect(function (err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = dbClient.db(dbName);
findTodos(db, function(todosArr) {
var todos = { todos: todosArr }
res.send(todos)
dbClient.close()
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
它基本上是从在线教程复制粘贴的。我第一次向“ http://localhost:3000/ ”发出 http 请求时,它可以工作。但我第二次得到
todo-backend/node_modules/mongodb/lib/utils.js:132
throw err;
^
AssertionError [ERR_ASSERTION]: 'MongoError: Topology was destroyed' == null
at todo-backend/index.js:15:16
at err (todo-backend/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback (todo-backend/node_modules/mongodb/lib/utils.js:404:25)
at handleCallback (todo-backend/node_modules/mongodb/lib/utils.js:128:55)
at cursor._endSession.cursor._endSession (todo-backend/node_modules/mongodb/lib/operations/cursor_ops.js:207:38)
at ClientSession.endSession (todo-backend/node_modules/mongodb-core/lib/sessions.js:129:41)
at Cursor._endSession (todo-backend/node_modules/mongodb-core/lib/cursor.js:189:13)
at Cursor._endSession (todo-backend/node_modules/mongodb/lib/cursor.js:226:59)
at cursor._next (todo-backend/node_modules/mongodb/lib/operations/cursor_ops.js:207:20)
at initializeCursor (todo-backend/node_modules/mongodb-core/lib/cursor.js:766:16)
我在互联网上寻找答案并发现了类似的错误,但是当人们做更复杂的事情时。我所做的似乎更基本,我找不到任何可能有帮助的改变空间。
如果我删除dbClient.close()
它,但我在 MongoDB 日志中看到连接数量在不断增长。当然,我可以引入一个标志并检查我是否已经连接。但是有了这个问题,我想了解根本原因。
解决方案
这是因为代码包含一个反模式:每次有新请求进入时,它都会打开一个新的数据库连接,然后在发送响应后关闭该连接。然后它随后尝试重用关闭的连接,因此您在第二个请求中看到了错误消息。
您想要的是使用全局连接对象在应用程序的生命周期内只连接一次数据库,然后使用该全局对象执行数据库操作。
使用这个全局对象允许 MongoDB 驱动程序正确地创建到数据库的连接池。该池由 MongoDB 驱动程序管理,避免了昂贵的连接/重新连接模式。
例如:
// listen on this port
const port = 3000
// global database client object
var client = null
// listen on the configured port once database connection is established
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, (err, res) => {
assert.equal(null, err)
client = res
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
})
// use the client global object for database operations
app.get('/', (req, res) => {
db = req.query.db
col = req.query.col
client.db(db).collection(col).find({}).toArray((err, docs) => {
assert.equal(null, err)
res.send(JSON.stringify(docs))
})
})
编辑以在评论中回答您的问题:
当我每次都连接时,为什么它会尝试重用以前的连接?
这是因为在原始代码中,dbClient
是全局定义的。当dbClient.close()
被调用时,全局dbClient
被关闭。dbClient
然后在重用该对象时产生错误。这是因为connect()
创建了一个连接池而不是单个连接,并且每次调用不会被多次调用。
如果将dbClient
变量从全局范围移动到app.get()
上下文中,您会发现多次调用 HTTP 端点时不会产生错误,因为dbClient
每次都会创建一个新对象。
话虽如此,尽管它会起作用,但这不是推荐的模式。最好使用类似于我上面发布的示例代码的模式。
推荐阅读
- python - 如何调试 Python 模块?
- ios - 无法验证 TNSWidgets.framework/TNSWidgets 中的位码
- opencv - 最佳方法:如何检测特征很少但成组出现的对象
- sql - 有更多行时执行 resultSet.next() 时出现 ArrayIndexOutOfBoundsException
- apache-kafka - 为什么 kafka-console-consumer 在少量消息上超时?
- javascript - 如何对 graphql 解析器实施保护
- visual-c++ - 如何使用适用于所有工作区的 Microsoft C++ 编译器配置 VS Code?
- python - 使用 Pyinstaller 编译为 exe 的 Pywinauto 脚本在本地执行,但不使用 PSEXEC 从 cmd 行远程执行
- java - 设置 JFrame 中可见空间的大小
- c# - 我想将一个 int "index" 参数传递给一个方法对话框,并要求用户输入一个他要搜索的特定值的字符串