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.
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:
2. Learn basics of MongoDB
3. Create a database and a collection of 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 MongoDB 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 MongoDB 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 onlinestoreuse 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
5. Dropping a database in mongoDB
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
> db.products.insert({'product_name': 'Google nexus', 'price': $500, 'category' : 'Mobile Phone'})
8. Dropping a collection – NodeJS mongodb tutorial
> db.products.drop() true
9. Datatype support in mongoDB
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
12. Save method in mongoDB
13. Select records from collection using find() method
> db.products.find();
14. Select records in a formatted way
pretty method displays results in a formatted way.>db.products.find().pretty()
15. Select a single document from a collection using findOne
findOne() method fetches a single document from a collectiondb.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 application. Like on windows type cd c:\ and then type following command.
express --view=jade onlinestore
Install dependencies
{ "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.
Find record from mongoDB using NodeJS
/* 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(); }); }); });
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
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 the client and is displayed in HTML form, button value changes from Add Records to Edit Records.
jQuery AJAX code to fetch the document from Server
In the code below the 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 the 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.
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('/'); } }); }); });
Running the application
To run this application, open command line, go to your project directory and type:
DEBUG=myapp:* npm start
Or
SET DEBUG=myapp:* npm start
Open browser and type URL:
http://localhost:3000
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 the tutorial source code from GitHub Repository
More Node.JS Learning Resources:
Related Articles:
- Generate CSV Using NodeJS and MongoDB
- NodeJS MongoDB Restful Web Services
- Chat Application Using NodeJs
- PHP MongoDB Tutorial
- Restful Web Services using CodeIgniter
- NodeJS PassportJS Login
Previous: NodeJS MySQL Pagination Next: PHP MongoDB Tutorial