Categories
JavaScript Answers

How to check if a collection exists in MongoDB native Node driver?

Spread the love

To check if a collection exists in MongoDB native Node driver, we call the listCollections method.

For instance we write

db.listCollections({ name: collName }).next((err, collinfo) => {
  if (collinfo) {
    // The collection exists
  }
});

to call listCollections with an object with the name property set to the collName collection name we’re looking for.

Then we call next with a callback that has the collection info set as the value of collinfo if it exists.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *