How to check if a collection exists in Mongodb native nodejs driver?
Solution 1:
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
}
});
Solution 2:
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.
Solution 3:
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
Solution 4:
Since MongoDB 3.0 you can simply run:
db.getCollectionNames()
which returns an array with the names of all the collections on current database:
[ "employees", "products", "mylogs"]
check Mongo DB Documentation, or you could also use db.getCollectionInfos() if you need more info about each collection
Solution 5:
There is now a listCollections method in Node.js native driver. It returns information on all collections in current database. You can use it to check if a given collection is there:
collectionExists = function(name, cb) {
mongoDb.listCollections().toArray(function(err, collections) {
if (err) return cb(err);
cb(null, collections.some(function(coll) {
return coll.name == name;
}));
});
}