It'sNotMe
It'sNotMe

Reputation: 1260

Mongoose - check if database exists

A Mongoose connection to a named Atlas database returns no error if the database does not exist. Connections are always successful as long as the URI and credentials are valid.

Is it possible to return an error if the specified database does not exist?

I'm modeling my app on Jelo's MERN write-up.

const mongoose = require("mongoose");
const Data = require("./data");

const API_PORT = 3001;
const app = express();
const router = express.Router();

// Atlas database
const uri = "mongodb+srv://USERNAME:[email protected]/"
const dbName = "fakedatabase"

const options = {
autoReconnect: true,
useNewUrlParser: true,
dbName: dbName
}

// Connect backend app to MongoDB with options
mongoose.connect(uri, options);
let db = mongoose.connection;

// connection event handlers
db.on("error", console.error.bind(console, "MongoDB connection error:"));
db.on("connected", console.error.bind(console, "MongoDB database: " + dbName));
db.on("disconnected", console.error.bind(console, "MongoDB database: " + dbName));

The code above returns:

MongoDB connected: fakedatabase

I'd like to trigger the "error" event handler and log the corresponding message.

Upvotes: 2

Views: 1510

Answers (1)

Ignacy Ruszpel
Ignacy Ruszpel

Reputation: 11

Not sure if it is possible to trigger the error event handler but you can check if database exists using listDatabases function from Mongo. Using Mongoose this can be done like this:

db.once("open", () => {
    new mongoose.mongo.Admin(db).listDatabases((err, res) => {
         //Array of databases is in res.databases   
    });
});

Upvotes: 1

Related Questions