Node.js 数据库关闭可能导致内存泄漏
我试图用setInterval执行一个函数,但有两个错误,第一个是Node.js 数据库关闭可能导致内存泄漏,node.js,mongodb,memory-leaks,Node.js,Mongodb,Memory Leaks,我试图用setInterval执行一个函数,但有两个错误,第一个是 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]
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")
}
我得到这个常量dataB=db(“AmerKorAsian”);^TypeError:db在Timeout.delete90[as _onTimeout](/Users/amerkorasian/back.js:138:19)选项2 i put const dataB=client.db(“amerkorasian”);其工作更新的答案,请检查