Insert Data in MongoDb Collection using Node.js


What do we intend to make ?

In this Chapter , we will insert data in the "details" collection we created in the previous chapter.

Let's Start !

Step - 1 : Including Packages
We will start by requiring the package. We are using the following package in our application :

		        

var mongo = require('mongodb');
                
	            


Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.

		        

var new_db = "mongodb://localhost:27017/demo_db"



                
	            

  • demo_db is the name of the database. You can change it as per your wish.
  • 27017 is the port where our mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step - 3 : Insert into DB
insertOne() is an inbuilt method which is used to insert data in the mongoDb collection.

		        
//insert_mongo_nodejs.js
mongo.connect(new_db , function(error , db){
	if (error){
		throw error;
	}
	
	var data = { name : "rishabhio" , age : "25" , mobile : "1234567890" }
	
	db.collection("details").insertOne(data, (err , collection) => {
		if(err) throw err;
		console.log("Record inserted successfully");
		console.log(collection);
	});
});


                
	            

You can run the above code using the following command :

		        

D:\nj-learn-mongo>node insert_mongo_nodejs.js

				
	            

The output of the above code is :

		        

D:\nj-learn-mongo>node insert_mongo_nodejs.js
Record inserted successfully
{ result: { ok: 1, n: 1 },
  connection: null,
  message: undefined,
  ops:
   [ { name: 'rishabhio',
       age: '25',
       mobile: '1234567890',
       _id: 597073b2c6f60f5b3c23a1a5 } ],
  insertedCount: 1,
  insertedId: 597073b2c6f60f5b3c23a1a5 
}