1

I want to create collection in mongoDB 4.2 but I want to check that is exist or not? I'm using Node.JS and Express and I'm NOT using Mongoose.

samurai_code
  • 57
  • 2
  • 9

2 Answers2

2

Please try this ::

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'your DB url';

// Database Name
const dbName = 'your DB name';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(async function (err) {
    if (err) console.log('Err::', err)
    console.log("Connected successfully to server");
    const collection = await client.db(dbName).listCollections({}, { nameOnly: true }).toArray()
    console.log('List of all collections :: ', JSON.stringify(collection))

    client.close();
});
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • Also `db.getCollectionNames()` should work in shell/any client like robo3T.. – whoami - fakeFaceTrueSoul Nov 21 '19 at 22:05
  • I got this error:Connected successfully to server (node:23868) UnhandledPromiseRejectionWarning: MongoError: MongoClient must be connected before calling MongoClient.prototype.db – samurai_code Nov 21 '19 at 23:10
  • @samurai_code : can you please edit your question with what you’ve tried, code !! – whoami - fakeFaceTrueSoul Nov 21 '19 at 23:13
  • @samurai_code : code should work after connectivity, an error might have been suppressed or so, So this error is due to improper connectivity, Please check this : https://stackoverflow.com/questions/55768876/mongoclient-must-be-connected-before-calling-mongoclient-prototype-db-on-heroku?noredirect=1&lq=1 – whoami - fakeFaceTrueSoul Nov 22 '19 at 06:20
  • @samurai_code : Or in general the other way if you don't want to do a db operation to get list of collections before creating one, then you can go ahead and do `createCollection()` it should error out if collection already exists in the same db. – whoami - fakeFaceTrueSoul Nov 22 '19 at 06:24
  • `db.listCollections({name:'test'}).then(function(collectionsList) { if(collectionsList){ //do something } })` Also this code is working for me – samurai_code Nov 22 '19 at 17:23
  • @samurai_code : yes either should work, difference is all about how you're writing code in js, async & await's are latest, it's ok it doesn't change functionality, but `db.listCollections({name:'test'})` vs `.listCollections({}, { nameOnly: true })` has difference first one will get you unnecessary information a lot of info, second one will get you least needed info, anyway if it's working as expected cool :-) – whoami - fakeFaceTrueSoul Nov 22 '19 at 17:37
0

You can use listCollections to find all the collection in your Database and loop over the returned array to get the names.

db.listCollections().toArray(function(err, items) {
    console.log(items)
        //and u can loop over items to fetch the names
  });
Shivam
  • 3,514
  • 2
  • 13
  • 27