我无法关闭mongoose连接,当我存储mongoose.connection在一个名为db
的变量中,并创建一个单独的方法来通过变量db
关闭连接我已经尝试了两种方法db.close
和mongoose.disconnect()
const mongoose = require('mongoose');
var db;
const connectToDB = function (callback) {
let dbUrl;
if (environmentTokens.enviroment === "test") {
dbUrl = localDBUrl;
} else {
dbUrl = environmentTokens.mongoDBUrl;
}
mongoose.connect(dbUrl);
db = mongoose.connection
db.on('error', (err) => {
tracer.error('Connection error with database', err);
})
db.on('connected', () => {
tracer.info('Connected with database', dbUrl);
console.log('Mongoose default connection connected');
callback();
})
};
const getDB = function () {
return db;
};
const disconnectDB = function () {
db.close(function () {
console.log('Mongoose default connection disconnected through app termination')})
// mongoose.disconnect(function () {
// console.log('Mongoose default connection disconnected through app termination')})
}
module.exports = {
connectToDB, disconnectDB, getDB
};
并从index.js
文件调用disconnectDB
方法
process.on('SIGINT', () => {
disconnectDB();
process.exit()
})
1条答案
按热度按时间dhxwm5r41#
连接正在关闭,但您的程序在调用回调之前退出。
要确认,请尝试:
第一个