Mongodb-node.js Tutorial Series

Insert data in mongodb collection using node.js

MongoDB-Nodejs tutorial | Perform mongodb operations using node.js


In this part of the mongodb operations using node.js tutorial series , we will insert data in mongodb collection using Node.js.

Let's Start !!
Step 1 - Include Package

We will start by including mongodb npm package as shown below :

var mongo = require('mongodb');

Step-2 : Establish Connection

Establish a connection between the mongoDb database and our node.js app using the following :

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

  • demo_db is the name of the database. You can change it in accordance with your database name.
  • 27017 is the port where mongoDb is running.
  • Localhost i.e. is the local IP.

Step - 3 : insert data

insertOne() is an inbuilt method which is used to insert data in mongodb collection as shown below:

var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db";

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");

You can run the above code using the following command :
>node insert.js
Record inserted successfully
{ result: { ok: 1, n: 1 },
  connection: null,
  message: undefined,
   [ { name: 'rishabhio',
       age: '25',
       mobile: '1234567890',
       _id: 597073b2c6f60f5b3c23a1a5 } ],
  insertedCount: 1,
  insertedId: 597073b2c6f60f5b3c23a1a5 

What we learned

In this article we learned about

  1. Including monogdb npm package in your app.
  2. Establishing a connection between mongodb database and node.js application.
  3. Insert data in mongodb collection using node.js