tony.0919
tony.0919

Reputation: 1203

How to check if db exists during mongodb connection using mongoose.connect?

I've tried to use mongoose.connect to check if a db exists,

mongoose.connect("mongodb://localhost:27017/notexistdb",function(err){
     if(err) console.log(err);
});

The callback doesn't contain error message, so how can I determine whether the database exists or not.

Upvotes: 3

Views: 7957

Answers (3)

Deepam Gupta
Deepam Gupta

Reputation: 2712

If you want to get your answer returned, you need to use the desync library.

Install desync using npm i desync

You can also use the following function in a different file by exporting it.

const mongoose = require("mongoose");
var Admin = mongoose.mongo.Admin;
const deasync = require("deasync");

function checkDatabase (dbName) {
  var check; // we will return this value
  var uri = "mongodb://localhost:27017/";

  // connect with mongoDB
  mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})
    .then(() => {
      new Admin(mongoose.connection.db).listDatabases((err, result) => {
        var allDatabases = result.databases;
        check = allDatabases.some((database) => database.name === dbName);
      });
    })
    .catch((err) => {
      console.log("some error occured");
    });

  // wait while mongoose executes the result
  while (check == null) {
    deasync.runLoopOnce();
  }

  return check; // either true or false
};

We need to use desync because much of the node's functionalities are asynchronous. To know more: Click Here - Callback Functions

Upvotes: 0

Bidhan
Bidhan

Reputation: 10697

You could try using open and error events to see if you can connect to the database. If you can connect to it, then it exists. If you can't, then it doesn't.

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:27017/notexistdb',function(err){
 if(err) console.log(err);
});

Upvotes: 0

karthick
karthick

Reputation: 6178

You can easily find out by getting database list.

var mongoose = require('mongoose')
    , Admin = mongoose.mongo.Admin;

/// create a connection to the DB    
var connection = mongoose.createConnection(
    'mongodb://user:pass@localhost:port/database');
connection.on('open', function() {
    // connection established
    new Admin(connection.db).listDatabases(function(err, result) {
        console.log('listDatabases succeeded');
        // database list stored in result.databases
        var allDatabases = result.databases;    
    });
});

Upvotes: 2

Related Questions