无法关闭node.js中的mongoose连接

jk9hmnmh  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(190)

我无法关闭mongoose连接,当我存储mongoose.connection在一个名为db的变量中,并创建一个单独的方法来通过变量db关闭连接我已经尝试了两种方法db.closemongoose.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()
})
dhxwm5r4

dhxwm5r41#

连接正在关闭,但您的程序在调用回调之前退出。
要确认,请尝试:
第一个

相关问题