node.js - 关闭 mongoDB 连接
问题描述
服务器没有关闭连接,我找不到错误。
当我第一次访问服务器(本地主机)时,它会返回正确的结果。
但是下一次,它会发送警告,例如
[MONGODB DRIVER] 警告:不支持选项 [caseTranslate]
还有更多。然后它返回“错误”
async function report(prodNum) {
try{
await client.connect();
let res = await findOneByprodNum(client, prodNum);
return res;
} catch (e){
return "Error";
} finally {
client.close();
}
}
async function findOneByprodNum(client, prodOfListing) {
const result = await client.db("mobileContents").collection("food").findOne({
prodNum: prodOfListing
});
if (result) {
console.log(`Found Name, in: ${prodOfListing}`);
console.log(result);
return result;
} else {
console.log(`No listings found, in: ${prodOfListing}`);
return null;
}
}
客户 =
const client = new MongoClient(uri, {
useUnifiedTopology: true,
useNewUrlParser: true,
connectTimeoutMS: 30000
});
解决方案
mongodb JS 驱动程序不是为关闭/重新连接而设计的
在应用启动时连接一次并共享client
. 退出节点进程时关闭。
const client = new MongoClient(uri, {
useUnifiedTopology: true,
useNewUrlParser: true,
connectTimeoutMS: 30000
});
async function startup(){
await client.connect()
}
async function shutdown(){
await client.close()
}
async function report(prodNum) {
try{
let res = await findOneByprodNum(client, prodNum);
return res;
} catch (e){
console.error(e)
return "Error";
}
}
推荐阅读
- keras - 在 ResNet50 Keras 中对自定义类进行分类(基本上是对冰淇淋的类型进行分类)
- python-3.x - 这是一个带有解决方案的练习,请在此向我解释一个 if 语句
- python - 遍历所有列表订单
- postgresql - 无法确定 postgres 超时的起源
- python - to_csv 不保存所有行?
- parallel-processing - 并行编程和计算
- python - 如何在 discord.py 中的某个时间间隔后向用户发送直接消息?
- python-3.x - askdirectory (tkinter) 中的选项“mustexist=False”
- android-studio - FLUTTER项目实施的一个问题
- asp.net - 在 WebMethod 中获取呼叫者 IP