node.js - 完成查询后正确关闭连接
问题描述
完成查询后,我不确定如何关闭连接
mongoose.connect("mongodb://localhost:27017/Settings", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
SettingsModel.create({ guildID: guild.id } as Settings, (err: string, res: any) => {
if (err) return console.error(err);
console.log(res);
});
解决方案
除非有特定原因要关闭连接,否则不应该 - 关闭和打开连接是密集且昂贵的。您打开一次连接并在您的应用程序运行时重用它。
建议在完全关闭应用程序时关闭所有连接 - 你可以这样做
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Disconnected db on app termination');
process.exit(0);
});
});
推荐阅读
- assembly - x64 支持是否意味着 BMI1 支持?
- bash - 如何用一个脚本杀死多个 PID 并使其返回提示
- c++ - 打开 CSV 文件进行阅读,但我不能
- c++ - 理解新关键字异常语法的问题
- c - 如何在 c 中使用 Dijkstra 的最短路径打印路径?
- statistics - 用至少一个其他值替换缺失值并删除所有值都缺失的情况
- shiny - 使用 shinywidgets 从 pickerInput 中删除“全选”操作按钮
- sql-server - 如何在 Linux/CENTOS 上为 SQL Server Developer Edition 启用 TCP/IP 协议
- angular - 我们应该如何更新另一个列表变量中的列表而不影响角度的父列表
- c++ - 无法调用基类成员函数,因为基类是模板化的