How to check if a collection exists in Mongodb native nodejs driver?

The collectionNames method of the native driver’s Db object accepts an optional collection name filter as a first parameter to let you check the existence of a collection:

db.collectionNames(collName, function(err, names) {
    console.log('Exists: ', names.length > 0);

In the 2.x version of the MongoDB native driver, collectionNames has been replaced by listCollections which accepts a filter and returns a cursor so you would do this as:

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

Leave a Comment