Home > Blockchain >  Function to check a collection is exist
Function to check a collection is exist

Time:05-16

I need to create a function or something else to check if a collection is exist.

  • If the collection exists - > .drop() and createCollection(nameCollection)
  • If the collection does not exist - > createCollection(nameCollection)

I know how to createCollection or drop, but I dont know how to create a function that will check is exist.

#Nodejs#Mongodb

CodePudding user response:

In mongodb nodejs we can use listCollections() method.

db(<databaseName>)
  .listCollections()
  .toArray()

to get all the collections in an Array and then we can use bunch of Array methods (like Array.indexOf()) to find out whether the collection exist or not.

Link to official Docs: listCollections

  • Related