Nodejs mongodb tutorial – find, insert, update, delete records

Nodejs mongodb tutorial

Web development field has evolved a lot in last decade. NodeJS became widely popular among web development community. It is a popular open source platform used for development of web and network centric applications. In a previous article NodeJS with mysql was explained. This nodejs mongodb tutorial explores how to select, insert, update and delete records from mongoDB database.

nodejs mongodb tutorial

MongoDB is a free and open source NoSQL database management system. It stores data as JSON key value pairs. In this nodejs mongodb tutorial we are going to:

1. Install mongodb

2. Learn basics of mongodb

3. Create a database and a collection with sample data

4. Install NodeJS and select data from mongodb using find method

5. Insert data into mongodb using insert method from NodeJS

6. Fetch record and update data in mongodb collection using update method in nodejs

7. Delete records from mongdb using deleteOne method from nodejs

Install MongoDb

MongoDB is a popular No-SQL document based database. It is known for scalability and performance. There are no tables or relations in mogodb as in relational databases like MySQL.

To install mongoDB community edition on Windows, Mac or Linux systems, please visit mongodb download page, and download appropriate mongodb installer. It is an easy wizard based process on windows. On mac you can unzip and rename the folder to mongodb. Detailed installation instructions can be found on mongodb installation page .

Running mongoDB

To run mongoDB first time, we first create data directory because mongod process will write to the data directory. Create a directory using command mkdir -p /data/db.

On command line open mongdb directory. Then go into bin directory. If system path variable is set, type mongod or  ./mongod otherwise type mongod –dbpath /path/to/data/directory.

Access interactive mongo shell

Open another command prompt window to access interactive mongo shell. If you have set system path already, then type mongo or ./bin/mongo. By default mongdb will connect to local host on port 27017.  It shows a startup message with mongdb version.

Basics of mongdb in nodeJs mongodb tutorial

1. Display all databases

To show all the databases, type command show dbs.

admin        0.000GB

local        0.000GB

onlinestore  0.000GB

2. Create or access a database in mongodb

use onlinestore
use command is used to access or create onlinestore database. If database does not exits, a new database is created.

3. Display current database name

To display  current database name type > db.

4. Display collections in a database

> show tables or > show collections command lists collections in a database.

5. Dropping a database in mongoDB

dropDatabase() command is used to drop a database. db.dropDatabase()

6. Create a collection in mongodb – NodeJS mongoDB tutorial

In onlinestore database, we need to create a products collection.

>db.createCollection("products")

{ "ok" : 1 }

7. Insert document in mongdb collection

Data can be inserted into a collection using insert or save methods. If you are inserting data into a collection that does not exit it is automatically created. You can specify any number of columns of different data types in a collection.
> db.products.insert({'product_name': 'Google nexus', 'price': $500, 'category' : 'Mobile Phone'})

8. Dropping a collection – NodeJS mongodb tutorial

In order to drop a collection we can use drop method.
> db.products.drop()
true

9. Datatype support in mongoDB

MongoDB supports string, integer, boolean, double, array, object, timestamp, null, objectID and other data types.

10. Insert array of documents into a collection

You can insert array of documents in to a mongdb collection as follows.

>db.products.insert([

{ "product_name" : "Apple IPhone 6", "price" : "$630", "category" : "Mobile Phone" },

{ "product_name" : "Sony Vio", "price" : "$1200", "category" : "Laptop" },

{ "product_name" : "Samsung T.V", "price" : "$900", "category" : "Electronics" },

{ "product_name" : "Apple IPAD", "price" : "$400", "category" : "Tablet" },

{ "product_name" : "MacBook Pro", "price" : "$800", "category" : "Laptop" }

])

11. Mongodb Objectid field

If _id field value is not provided mongodb creates a hexadecimal field for _id field that is used as a primary key. Every document in a mongodb collection requires an _id field. It is an auto generated 12 bytes field consisting of 4 bytes for seconds from UNIX timestamp, 3 bytes of machine identifier, 2 bytes of process id and 3 bytes for a counter.

12. Save method in mongoDB

save() method can be used to insert or update documents. If _id parameter is specified update of document is performed otherwise insert of  document occurs.

13. Select records from collection using find() method

In order to fetch records from a collection find() method is used. If no parameter is specified it selects all the records in a collection.
> db.products.find();

14. Select records in a formatted way

pretty method displays results in a formatted way.

>db.products.find().pretty()

nodejs mongodb tutorial - display reocds using pretty method

15. Select a single document from a collection using findOne

findOne() method fetches a single document from a collection

db.products.findOne()


{
  "_id" : ObjectId("589a18039341bf7e6dad5f84"),
  "product_name" : "Apple Watch",
  "price" : "$410",
  "category" : "Electronics"
}

Installing NodeJS

To download and install NodeJS visit nodejs download page. Download and run installer. After installation completes, open command prompt and type node -v. Current installed version of NodeJS is displayed.

Install Express Generator

Next you are going to install express generator.

npm install express-generator -g

After installation go to the directory where  you want to create you application. Like on windows type cd c:\ and then type following command.

express --view=jade onlinestore
This sets view template engine to jade and generates an application skeleton for onlinestore as under
nodejs mongodb tutorial - express generated app skeleton

Install dependencies

As shown in the image, type cd onlinestore and then enter $ npm install command, It will install all dependencies and packages inside node_modules folder, These dependencies or packages are defined in package.json file.
{
  "name": "onlinestore",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.16.0",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.0",
    "express": "~4.14.1",
    "jade": "~1.11.0",
    "morgan": "~1.7.0",
    "serve-favicon": "~2.3.2"
  }
}

To access mongoDB with NodeJS you need to install MongoDB driver. Please type  npm install –save mongodb. To run application type

DEBUG=onlinestore:* npm start

On a Windows system run

set DEBUG=onlinestore:* npm start

Open project folder in your favorite IDE. Generated application structure can be seen.

nodejs mongodb tutorial - express generated folder structure
Now inside routes folder open index.js file. Delete all existing code.

Find record from mongoDB using NodeJS

In order to fetch records from mongoDB database find() method is used.
/* NodeJs mongodb tutorial - insert update delete records */

var express     = require('express');

var router      = express.Router();

var mongodb     = require('mongodb');

var MongoClient = mongodb.MongoClient;

var dburl = "mongodb://localhost:27017/onlinestore";

The code above requires express, mongodb modules. We are going to use MongoClient to connect and access database on localhost via port 27017.

Find records from database

First we define / route in index.js. Secondly inside router  connect to database server using MongoClient.connect method. Local database URL passed to method. To fetch data from products collection, collection name is passed to db.collection method.

find method queries the collection and retrieves cursor for the result set. To use the cursor results it is converted into an array by using .toArray() function. View file index.jade page is rendered using response object render method. Returned data is also passed to the view file.

/* GET products listing. */
router.get('/', function(req, res, next) {

  MongoClient.connect(dburl, function(err, db) {

    if(err) {  console.log(err); throw err;  }

    data = '';

    db.collection('products').find().toArray(function(err, docs){

      if(err) throw err;

      res.render('index.jade', {data: docs});

      db.close();

    });

  });

});
 In the image below _id, product name, price and category values are displayed.nodejs mongodb tutorial - find records

Create view index.jade file

To display records in Jade view file open views folder and add the code below into index.js file. extend layout line tells that this document is extending the layout.js. In content block a form is created to add or edit records. HTML table displays headers for product name, price , category and action field.

If  there are data rows returned from server and each loop is executed and displays the values for the document in table cells. Under action field edit and delete links are displayed. A class .editlink and a data attribute data-id is added to edit link so it can be used when edit link’s click event is fired. Clicking on Delete link a confirmation message is displayed if user clicks ok button request is posted to delete route and document is removed from database.

extends layout
block content
  .container
    h2 NodeJs MongoDB example - View Insert, Update, Delete records
    .success
    .error
    form(id='form1' action='/add' method= 'post')
      input#id(type='hidden', name='id', value='')
      table
        tr
          td(style='text-align: center')
            input#product_name(type='text', name='product_name', placeholder='Product Name', value='')
            |      
            input#price(type='text', name='price', placeholder='Price', value='')
            |      
            input#category(type='text', name='category', placeholder='Category', value='')
            |      
            input#subbtn(type='submit', name='sub', value='Add Product')
    table
      tbody
        tr
          th ID
          th Product Name
          th Price
          th Category
          th Action
        if data.length
         each item in data
          tr
            td #{item['_id']}
            td #{item['product_name']}
            td #{item['price']}
            td #{item['category']}
            td
               a.editlink(href='javascript:void(0)', data-id='#{item["_id"]}') Edit
               |   
               a(href='/delete?id=#{item["_id"]}', onclick='return confirm("You are going to delete this record. Continue?")') Delete

Insert records – NodeJS MongoDB tutorial

To insert records into a mongoDB collection using NodeJS first a route add is added in index.js file. Inside route connect to mongodb database, In case of success db object is returned else an error is thrown. We pass products collection to db.collection method.
Next a JavaScript object with product_name, price and category is created. Product object and callback function is passed to insert method. If insert is failed an error is thrown otherwise user is redirected to / route.
router.post('/add', function(req, res, next) {

  MongoClient.connect(dburl, function(err, db) {

    if(err) { throw err;  }

    var collection = db.collection('products');

    var product = {  product_name: req.body.product_name,  price:req.body.price, category: req.body.category };

    collection.insert(product, function(err, result) {

    if(err) { throw err; }

      db.close();

      res.redirect('/');   
  });

  });

});

 Update records – NodeJS mongoDB tutorial

To update records in a mongoDB database using NodeJS, user clicks on Edit link an AJAX request is sent to server with id of record. Server returns the existing values of the document to client and are displayed in HTML form, button value changes from Add Records to Edit Records.

jQuery AJAX code to fetch document from Server

In the code below first jQuery is included from jQuery CDN. Inside jQuery load function a click event handler created for the edit class that is applied to each edit link in records. When any of edit link is clicked this event handler is called. A data-id attribute is defined with _id value that is primary key of each document.

AJAX request is sent to fetchdata page with id field. On successful completion of request data is returned to .done function. Inside .done function values of product_name, price, category and id are assigned to form fields. _id field value is assigned to a hidden field value so it can be posted to the server with other data.

script(src='https://code.jquery.com/jquery-3.1.1.min.js')

    script.

      $(function() { 

        $('.editlink').on('click', function(){

          var id = $(this).data('id');

          $.ajax({

            method: "GET",

            url: "/fetchdata",

            data: { id:  id },

          }).done(function( data ) {

            $('#id').val(data[0]['_id']);

            $('#product_name').val(data[0]['product_name']);

            $('#price').val(data[0]['price']);

            $('#category').val(data[0]['category']);

            $("#subbtn").val('Edit Product');

            $('#form1').attr('action', '/edit');

          });

        });

      });

 Fetch a single document from database

Create a route fetchdata in index.js file. This route gets id parameter from client request and connects to mong0DB database. It connections is not successful an error is thrown. db.collections is passed products collection. Inside find method document id is passed as criteria. On success data is sent back to client.

router.get('/fetchdata', function(req, res, next) {

   var id = req.query.id;

   MongoClient.connect(dburl, function(err, db) {

    if(err) {  throw err;  }

    db.collection('products').find({_id: new mongodb.ObjectID(id)}).toArray(function(err, docs){

      if(err) throw err;

      res.send(docs);

      db.close();

    });

  });

});

After data is received and displayed in form User makes changes to record and clicks Edit Product button. Form is posted to Edit page.

nodejs mongodb tutorial - edit records

 

Add code below in index.js file to create edit route. After connection to database, products collection is passed to db.collection. Next a JavaScript object is created with product, price and category fields.

In Collection’s update method first a criteria is passed that is _id of the document to be updated. Then updated document and a callback function is passed. Inside callback function result and error is returned. An error is thrown in case of error otherwise user is redirected to ‘/’ route.

router.post('/edit', function(req, res, next){ 

  MongoClient.connect(dburl, function(err, db) {

    if(err) { throw err; } 
    
    var collection   = db.collection('products'); 

    var product_name = req.body.product_name;

    var price               = req.body.price;

    var category     = req.body.category;

    collection.update({'_id':new mongodb.ObjectID(req.body.id)}, 
    { $set: {'product_name': product_name, 'price': price, 'category': category } }, function(err, result) { 

      if(err) { throw err; } 
      
      db.close(); 
      
      res.redirect('/'); 

    }); 

  });

});

Delete records

Create a route /delete in index.js file. Callback function accepts a request, response and next parameters. Inside callback function connection to mongodb database is created using mogoClient.connect. products collection is passed to db.collection method.

In callback function deleteOne method is called with id parameter as mongodb objectID. If document is successfully deleted then user is redirected to ‘/ ‘ route to view records otherwise an error is thrown.

router.get('/delete', function(req, res, next) {
 
  var id = req.query.id;
 
  MongoClient.connect(dburl, function(err, db) {

    if(err) { throw err;  }

    db.collection('products', function(err, products) {

      products.deleteOne({_id: new mongodb.ObjectID(id)});

      if (err){
  
       throw err;
   
      }else{
    
         db.close();
          res.redirect('/');
    
       }

    });

  });

});

 Summary

In summary in this nodejs mongodb tutorial you learned how to fetch, insert, update, and delete records from mongodb collection. You can find source code in the link given below. Please leave your valuable feedback and comments.

Click to download tutorial source code

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

About Jason William

  • Pingback: Nodejs mongodb tutorial - find, insert, update,...()

  • Pingback: php mongodb tutorial - find, insert, update and delete records()

  • Pingback: NodeJS Passport login script with MySQL database()

  • Dock

    how do you run this scripts? I appreciate your work but as a newbie trying to learn mongodb working with Node.js i found the instruction a bit obscure and unclear (I cannot follow your instruction). I hope you can improve it so everyone can follow it. Yes I downloaded the source code but I don’t know how to run it.

    • jason

      Hi Dock,

      Thanks for your comment. To run the scripts you need to
      install MongoDB and NodeJS on your system, Whether you are using Mac,
      Linux or Windows.

      Steps are explained below.

      a. Running MongoDB

      1. First you need to install mongoDB on your system. If you are using Mac
      please read Install MongoDB and Running MongoDB section above. On a Windows System download MongoDB set up and install on you system.
      https://www.mongodb.com/download-center#community

      2. After mongoDB installation go To Command Line: To run mongoDB first time, You need to create a Data folder because mongod process will write to the data directory. So suppose if you are using Windows, Create folder
      data

      in C: drive. Like C:data

      3. Open a command line window and go to bin folder in MongoDB installation
      directory. like if you installed mongoDB in C: drive then go to

      C:/mongodb/bin.

      4. Type command ->mongod or -> ./mongod

      5. Open an other command line and go to C:/mongodb/bin and type command
      -> ./mongo or -> mongo

      6. MongoDB will start running on your system .Please type the commands above in article.
      7. You can run the commands to create a database and insert data to a collection as described above

      Running NodeJs

      1. Next you need to install NodeJS on your system. Please visit https://nodejs.org/en/download/ and download and Install NodeJS on you system.

      2. After NodeJS download Open Command Prompt and
      type -> node -v
      This will show your current installed NodeJS version.

      Running the example Code

      1. To run the example code on you system (Suppose you are using Windows)
      Copy and paste the onlinestore directory to C:/ drive

      2. Open Command Line and Go to C:/ drive

      3. Type Command

      set DEBUG=onlinestore:* npm start

      4. This will start a NodeJS web server on port 3000

      5. Now Open Web browser and in address bass type:

      http://localhost:3000

      you can see the NodeJS application running.

      Creating the application from Scratch

      3. To create this application from scratch install MongoDB, NodeJS and express generator and express on your system on command line

      https://expressjs.com/en/starter/generator.html.

      4. After installing express generator. you always need to type command.

      To create a NodeJS app.

      express –view=pug yourprojectname

      This will generate a NodeJS and express project for you.

      Next
      Type: cd yourprojectname
      Type: npm install

      Type :

      DEBUG=myapp:* npm start

      or

      SET DEBUG=myapp:* npm start

      Then open browser and type address: http://localhost:3000

      You can see a basic NodeJS, Express app running. You can open index.js from routes folder and add code to it. Restart app and you can see the changes.

      I hope you will be able to run the application . If you still face any issue please let us know, and we will be glad to help.

      • Dock

        Thank you, thank you, thank you. I will try it and I am sure I will come back with some questions. Absolutely brilliant.