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

Nasser Torabzade picture Nasser Torabzade · Jan 9, 2014 · Viewed 80.6k times · Source

I need to check if a collection exists on a certain database and create it if it doesn't. I know that

db.createCollection(collName, {strict:true}, function(error, collection))

checks for existance of collection collName before creating it and sets error object. but I need an independent function to check that.

Answer

JohnnyHK picture JohnnyHK · Mar 7, 2015

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
        }
    });