首页 > 解决方案 > 数据库关闭可能导致内存泄漏

问题描述

我正在尝试使用 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()

标签: node.jsmongodbmemory-leaks

解决方案


问题 - 您每次都在创建一个新连接。

解决方案 - 连接一次并缓存连接

选项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")
}

推荐阅读