Node.js – Create Database in MongoDB

In this Node.js Tutorial, we shall learn to Create Database in MongoDB from Node.js Application with an example.


Following is a step by step guide with an example to create a database in MongoDB from Node.js Application.

  1. Start MongoDB Service. Run the following command to start MongoDB Service
  2. Install mongodb package using npm. Refer Node.js MongoDB Tutorial to install mongodb package.
  3. Get the base URL to MongoDB Service. A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell. While the Mongo Shell starts up, it echoes back the base url of MongoDB.
  4. Prepare the complete URL. Append the Database name you want to create (say newdb), to the base URL.
  5. Create a MongoClient.
  6. Make connection from MongoClient to the MongoDB Server with the help of URL. [Note : In MongoDB, creating Database is an implicit process.] Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.

    If the connection is successful, the db object points to the newly created database newdb.

Example Node.js program


MongoDB Tutorial – Learn MongoDB from basics with Examples.

Conclusion :

In this Node.js MongoDB tutorial : Node.js – Create Database in MongoDB, we have learnt to create a database from Node.js Application using mongodb package. In our next tutorial – Node.js MongoDB Drop Database, we shall learn to delete the database.