Load a mongo collection without creating it if not exists

102 Views Asked by At

with mongo db node driver v4.13, how can I load a mongo collection without creating it if not existing?

In earlier versions the function db.collection can be called like this:

db.collection('not_existing', { strict: true }, (err, res) => {
  if (err) {
    console.log('Collection does not exist');
  }
});

But in v4.13 the callback version of this function does not exist anymore and strict: true seems to be ignored.

const collection = await db.collection('not_existing', { strict: true });

console.log(await db.listCollections().toArray()); // lists the collection
1

There are 1 best solutions below

0
Wernfried Domscheit On

You can use

db.getCollectionNames().filter(x => x == 'not_existing').length > 0

or

db.runCommand({ listCollections: 1, filter: { name: 'not_existing' } }).cursor.firstBatch.length > 0

to check whether a collection exists or not.