Nodejs MongoDB create collection

MongoDB’s collection is like a table in RDBMS. to create the collection through createCollection() method.

Firstly create the create_collection.js file.


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

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.createCollection("users", function(err, res) {
      if (err) throw err;
       console.log("Collection is created");
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the create_collection.js file.


node create_collection.js
Output:-
Collection is created

Note:- If you have not collection then you create a document then it will check collection is exists or not it does not exists then it will create the collection.