我希望Mongoose在退出程序时断开连接,而不管它是手动退出(Ctrl + C),正常退出(到达程序末尾)还是由于运行时错误。
这是我的代码:
require('dotenv').config()
const log = require('./middleware/log')
const error = require('./middleware/error')
const mongoose = require('mongoose');
(async () => {
// handle Ctrl+C
process.on('SIGINT', () => {
process.exit(2)
})
// log program exit
process.on('exit', (code) => {
if (code === 2) {
log('Program exited manually.')
} else if (code === 1) {
log('Program crashed.')
} else {
log('Program exited.')
}
mongoose.disconnect()
.then(() => {
process.exit(code)
})
})
await mongoose.connect(
'mongodb://' + process.env.MONGO_USER_DEV + ':' + process.env.MONGO_PW_DEV + '@' + process.env.MONGO_IP_DEV + ':' + process.env.MONGO_PORT_DEV + '/' + process.env.MONGO_DB_DEV,
{
useNewUrlParser: true
}
)
// do stuff
})().catch(err => {
error(err)
})
程序结束时,它只是挂起。我在做什么错了?