Mongoose detect database not ready

后端 未结 4 1015
暖寄归人
暖寄归人 2021-01-11 19:27

Is it possible to detect that the database is not running with Mongoose ?

相关标签:
4条回答
  • 2021-01-11 19:51

    You can tell if mongoose is already connected or not by simply checking

    mongoose.connection.readyState
    0 = no
    1 = yes
    
    0 讨论(0)
  • 2021-01-11 19:51

    The straight forward works fine for me:

    mongoose.Connection.STATES.connected === mongoose.connection.readyState

    0 讨论(0)
  • 2021-01-11 19:58

    Apparently Mongoose it self doesn't throw any exceptions.

    So you can use the Mongo DB Native NodeJS Driver:

    So here's what you can do:

    var mongoose = require('mongoose');
    
    var Db = require('mongodb').Db,
        Server = require('mongodb').Server;
    
    console.log(">> Connecting to mongodb on 127.0.0.1:27017");
    
    var db = new Db('test', new Server("127.0.0.1", 27017, {}));
    
    db.open(function(err, db) {
        console.log(">> Opening collection test");
        try {
            db.collection('test', function(err, collection) {
                console.log("dropped: ");
                console.dir(collection);
            });
        }
        catch (err) {
            if (!db) {
                throw('MongoDB server connection error!');
            }
            else {
                throw err;
            }
        }
    });
    
    process.on('uncaughtException', function(err) {
        console.log(err);
    });
    
    0 讨论(0)
  • 2021-01-11 20:05

    I would recommend using the open and error events to check if you can connect to the database. This is a simple example used in all my projects to double check that I'm connected.

    var mongoose = require('mongoose');
    
    mongoose.connection.on('open', function (ref) {
      console.log('Connected to mongo server.');
    });
    mongoose.connection.on('error', function (err) {
      console.log('Could not connect to mongo server!');
      console.log(err);
    });
    
    mongoose.connect('mongodb://localhost/mongodb');
    
    0 讨论(0)
提交回复
热议问题