How to check if a database exists with mongoose.createConnection()?

依然范特西╮ 提交于 2019-12-07 21:45:17

问题


I want to create multiple connections using mongoose. Therefore, I've chosen to use mongoose.createConnection() instead of mongoose.connect().

When I connect on my localhost, I want to check if the database that I'm connecting to exists.

My connection to a non-existing database:
let db = mongoose.createConnection('mongodb://localhost/nonexistentdb');

Nevertheless, the events still give the the following results:

db.on('open', function() {
    console.log("Opened"); // <= logged
});

db.on('connected', function () {  
    console.log('Connected'); // <= logged 
});

db.on('error', (err) => {
    console.log("Unable to connect to database"); // <= not logged
});

Note: It does log the error event on a non-existing database when using mongoose.connect().

How do I check for database existence using mongoose.createConnection()?

来源:https://stackoverflow.com/questions/34232183/how-to-check-if-a-database-exists-with-mongoose-createconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!