Insert a document using NodeJs and mongoDB

Insert a document using Node.js and mongoDB

Suppose  you have a mongoDB database for courses and you want to insert a record into the database using Node.js.

First step is to install mongoDB driver for Node.js  If it is not already installed. Please open command line and run following command.

This will install mongoDB driver for node js.  This command will install mongoDB driver for Node.js. After successfully installation we  move to NodeJs part of  our script.

Create a script named insert.js. and then add following code


Here is explanation of the code above.

1.  Include mongoDB module

Above line is used to include mongoDB module to use in script.

2. Connect and Insert a document to MongoDB

The code line below is using connect method of MongoClient, Inside connect method a connection string is passed with port number 27017 , and suppose the database or collection name is course. second parameter is a callback function that will be called after connection is made to the database and it receives the parameters err and db.

While making a connection to database server  if there is some error the line below will throw an error.

If there is no error then we create a new document in an object named doc with following values.

The line below executes a command to insert the doc object into students table. For this purpose we use db object’s collection method and pass  ‘students’ table as parameter.

After collection method we have called insert method and pass it two parameters. First parameter is doc object and second parameter is a callback function that has two parameters. First parameter to callback is err while second parameter is inserted . Inserted are the docs that are inserted into database.

if docs are successfully inserted the following code will run.

We will see message “Successfully inserted”.  and then db object is closed.

In command prompt use this command to run the above script.

After sucessfull query execution we wil se the message

In mongoDB shell in course database if we run the command.

we will get the result.

In next tutorials we will explore advance topics in Node.js and MongoDB.


  1. By Ramesh


  2. By Maz


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.