Dark Mode
Image

Node.js MongoDB Create Database

to create a database in MongoDB, First create a MongoClient object and specify a connection URL with the correct ip address and the name of the database which you want to create.

Note: MongoDB will automatically create the database if it does not exist, and make a connection to it.

Example

Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a js file named "createdatabase.js" within that folder and having the following code:

  1. var MongoClient = require('mongodb').MongoClient;  
  2. var url = "mongodb://localhost:27017/MongoDatabase";  
  3. MongoClient.connect(url, function(err, db) {  
  4. if (err) throw err;  
  5. console.log("Database created!");  
  6. db.close();  
  7. });  

Now open the command terminal and set the path where MongoDatabase exists. Now execute the following command:

  1. Node createdatabase.js 

Comment / Reply From