In this tutorial you will learn about the Nodejs MongoDB Create Database and its application with practical example.
Node.js MongoDB Create Database
In order to create a MongoDB database , we have to first create a MongoClient object, then to pass a connection URL with the correct ip address and the name of the database you would like to create. MongoDB engine first check for the database if it does not exist then it creates and make a connection to the database.
Example :- Let’s create MongoDB database named as “nodemongo”
Step 1:- Let’s, create a node_mongo_create_db.js file and put the following code in it –
1 2 3 4 5 6 7 |
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/nodemongo"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("W3Adda | MongoDB Database created!"); db.close(); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mongo_create_db.js |
you will see following output on terminal –
Output:-
1 |
W3Adda | MongoDB Database created! |