NodeJS Mongoose& Mongo Db连接问题

时间:2018-03-08 13:47:56

标签: node.js mongodb mongoose

我是mongodb的新手,我已在mac os上设置并且已成功完成。现在,当我使用mongoose运行我的节点js应用程序以连接mongodb时,它始终显示连接状态

我使用下面的代码来连接数据库。

module.exports = function() {
    /**
     * Requiring this module will populate the mongoose connection pool.
     * Any models defined on mongoose will be ready to use (mongoose is
     * a singleton).
     */
    var mongoose = require('mongoose');
    var logger = include('logger.js');

    // attempt to connect to the database server
  logger.info("DB CONNECTION ", {DB: global.settings.DB, options: global.settings.DbOptions});
  //console.log("DB CONNECTION ", {DB: global.settings.DB, options: global.settings.DbOptions});

    mongoose.connect('mongodb://localhost/circleweb');
    mongoose.connection.on("open", function(ref) {
      console.log("Connected to mongo server.");
    });
    mongoose.connection.on('connected', function () {
        console.log('connected');
        console.log('Mongoose default connection open to ' + global.settings.DB);
    });

    mongoose.connection.on('error', function (error) {
        logger.error(error);
        console.log('Mongoose default connection error: ' + error.err);

        // if the database cannot be connected to.  We are going to throw
        // an error.  This will be caught by the error handler
        throw error.err;
    });

    mongoose.connection.on('disconnected', function () {
        console.log('Mongoose default connection disconnected');
    });

    process.on('SIGINT', function () {
        mongoose.connection.close(function () {
            console.log('Mongoose default connection disconnected through app termination');
            process.exit(0);
        });
    });

    console.log(mongoose.connection.readyState);
    return mongoose.connection;

}();

当我运行我的应用程序时,我没有收到来自mongoose的任何回调,甚至没有任何错误。

此外,当我在终端上运行mongod时,它显示正确的输出,并且它还接受来自nodejs应用程序的连接但未连接它。

任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:0)

因为console.log(mongoose.connection.readyState)正在同步运行 - 它将首先执行 - 在mongoose.connection.on异步调用之前,这意味着状态为2或连接。

将其置于超时范围内,您将获得预期的1值:

setTimeout( () => {
  console.log(mongoose.connection.readyState); // prints 1
}, 2000);

或者在异步调用中打印状态:

mongoose.connection.on('connected', function () {
  console.log(`STATE: `, mongoose.connection.readyState);
  console.log('connected');
  console.log('Mongoose default connection open to ' );
});