NodeJS-猫鼬连接未定义,无法关闭

时间:2018-07-05 01:21:45

标签: node.js mongodb mongoose connection

我正在编写一个节点应用程序,以将服务器ping自动存储在Mondo数据库中。我能够连接,填充和清除数据库而没有任何错误;但是,当我尝试关闭连接时,我得到TypeError: Cannot read property 'close' of undefined。当我在不尝试断开连接的情况下运行代码时,它可以正常运行,但可以无限期运行(我必须手动停止程序)。这是我的数据库服务脚本:

const mongoose = require('mongoose');

// Connect to DB
const connect = () => {
  mongoose.connect('mongodb://user:password@localhost:8080/cx', {
    auth: { authdb: 'admin' },
  }).then(() => {
    console.log('Connection successful to', mongoose.connection.db.s.databaseName);
  }).catch((err) => {
    console.log("ERROR:\n", err);
  });
};
connect();

// Entry model
const Entry = mongoose.model('Entry',
  mongoose.Schema({
    server: String,
    statusCode: Number,
    time: Number,
  }, {
    versionKey: false,
  }),
  'healthChecks');

module.exports = {

  // Add entry to database
  logEntry: (server, statusCode, time) => {
    connect();
    const db = mongoose.connection;
    db.setMaxListeners(0); // disable max listeners for adding multiple entries
    db.on('error', console.error.bind(null, ({
        message: "Connection failed. Check connection to the Internet",
      })
    ));
    db.once('open', () => {
      const status = new Entry({
        server,
        statusCode,
        time,
      });
      status.save((err) => {
        if (err) throw err;
      });
    });
    mongoose.disconnect() // error is thrown here
      .catch((err) => {
        throw (err);
      });
  },

  getModel: Entry,

  dropCollection: () => {
    Entry.remove({},(err) => {
      console.log('collection removed')
    });
  }

};

mongoose.disconnect()行引发了错误,但是当我使用mongoose.connection.close()时也遇到了相同的错误。我在Docker上运行mongo,而不是在使用mongod。我是Node的新手,但是我在Mongo上有很多经验。任何帮助将不胜感激,谢谢!

0 个答案:

没有答案