Mongoose detect database not ready

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

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

4条回答
  •  离开以前
    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');
    

提交回复
热议问题