node.js - 数据库关闭可能导致内存泄漏
问题描述
我正在尝试使用 setInterval 执行一个函数,但我遇到了 2 个错误,第一个是
node:88454) [MONGODB DRIVER] Warning: the options [servers] is not supported
(Use `node --trace-warnings ...` to show where the warning was created)
(node:88454) [MONGODB DRIVER] Warning: the options [caseTranslate] is not supported
(node:88454) [MONGODB DRIVER] Warning: the options [dbName] is not supported
第二个是
(node:88384) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 newListener listeners added to [MongoClient]. Use emitter.setMaxListeners() to increase limit
我不认为增加setMaxListeners
是我认为与关闭客户端有关的答案我如何解决这个问题?代码如下:
客户:
const client = new MongoClient(cred.dbUri, {useUnifiedTopology: true})
相关功能:
async function delete90(){
await client.connect(()=>{})
const dataB = client.db("AmerKorAsian");
const coll = dataB.collection("users");
await coll.deleteMany({
"Full Name":"",
"Contact.Country":"",
"Contact.Number":""
})
console.log("interval")
}
setInterval(delete90, 1000);//777600000
client.close()
解决方案
问题 - 您每次都在创建一个新连接。
解决方案 - 连接一次并缓存连接
选项1
let connection;
async function connect() {
if(!connection) {
await client.connect(()=>{});
connection = client.db;
}
return connection;
}
async function delete90(){
const db = connect();
const dataB = db("AmerKorAsian");
const coll = dataB.collection("users");
await coll.deleteMany({
"Full Name":"",
"Contact.Country":"",
"Contact.Number":""
})
console.log("interval")
}
选项 2
let usersCollection;
async function getUserCollection() {
if(!usersCollection) {
await client.connect(()=>{});
const dataB = client.db("AmerKorAsian");
usersCollection = dataB.collection("users");
}
return usersCollection; // cache and return the collection
}
async function delete90(){
const coll = await getUserCollection();
await coll.deleteMany({
"Full Name":"",
"Contact.Country":"",
"Contact.Number":""
})
console.log("interval")
}
推荐阅读
- excel - 如何获取代码以正确计算一个电子表格中的项目(变量)并成功显示此信息?
- mongodb - 将 GeoJSON 中的 OSGridRef 转换为 MongoDB 索引
- python - pycaret 上的概率与预测的标签不匹配
- python - 如何使代码以更pythonic的方式
- json - 带有listview颤动的嵌套Json
- r - 具体变量计算
- javascript - Reactjs/Nextjs 和 Mongodb 中的轮播实现在元素定义时返回错误
- reactjs - 使用不存在的值作为带有useEffect React Hook的参数时如何修复缺少的依赖警告?
- typescript - 计算一个时间段有多少个月
- xcode - 添加 DCMTK 库并为 Xcode 12.4+ 编译