首页 > 解决方案 > 完成查询后正确关闭连接

问题描述

完成查询后,我不确定如何关闭连接

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);
});

标签: node.jsmongodbmongoose

解决方案


除非有特定原因要关闭连接,否则不应该 - 关闭和打开连接是密集且昂贵的。您打开一次连接并在您的应用程序运行时重用它。

建议在完全关闭应用程序时关闭所有连接 - 你可以这样做

process.on('SIGINT', function() {
  mongoose.connection.close(function () {
    console.log('Disconnected db on app termination');
    process.exit(0);
  });
});

推荐阅读