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

In MongoDB 3.0 and later, you have to run a command to list all collections in a database:

use test;
db.runCommand( { listCollections: 1 } );

Although querying system.namespaces will still work when you use the default storage engine (MMAPv1), it is not guaranteed to work for other engines, such as WiredTiger.

Before MongoDB 3.0 you need to do the following:

You can query the system.namespaces collection:

use test;
db.system.namespace.find( { name: 'test.' + collName } );

Like in:

db.system.namespaces.find( { name: 'test.testCollection' } );

Which returns:

{ "name" : "test.testCollection", "options" : { "flags" : 1 } }

Or of course, nothing.

See also: https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst


Using mongo-native driver and Node.js 7.6+, I use the following:

const collections = await db.collections();
if (!collections.map(c => c.s.name).includes(collName)) {
    await db.createCollection(collName);
}

EDIT

As @MattCochrane mentions, collection.s.name is no longer available; as @JohnnyHK and @weekens point out, the correct way is to use the listCollections() method:

const client = new MongoClient(connectionString, { useUnifiedTopology: true });
await client.connect();
const collections = await client.db().listCollections().toArray();
const collectionNames = collections.map(c => c.name);

listCollection() takes an optional filter.