In this post we will look at how we can implement CRUD operations using Node.js and MongoDB as the database. CRUD stands for Create Read Update Delete. The programming language we would use for this is Javascript based Node.js (Read : Introduction to Node.js) framework and MongoDB as the NoSQL database. And this example is going to be command line based and hence we will be taking user input from command line. If you have any questions, please write it in the comments section or post it in our facebook page.
To demonstrate CRUD operations I am picking a common example of storing, retrieving, updating and delete a book from the DB. The book has the following attributes: name, isbn, authors, page count. At the end of this post, I have given the complete example code for Node.JS and MongoDB integration example. In my next article, I will write about using Mongoose to facilitate the database modeling with Node.js.
also read:
This post is divided into following parts:
- Reading user input from command line in Node.js
- Connecting to MongoDB in Node.js
- Inserting record into MongoDB in Node.js
- Listing/Reading records from MongoDB in Node.js
- Updating records in MongoDB in Mode.js
- Deleting records from MongoDB in Node.js
- Node.js and MongoDB Integration Example
Reading user input from command line in Node.js
Node.js organizes the code into different Node packages ( think of them as packages in Java) and we can use those packages/modules by using the require
function. On similar lines, there is a module in Node.js called readline
which provides APIs to read from different input streams. The below code demonstrates how one can read from command line in Node.js
//input.js //Importing the relevant module var readline = require('readline'); //Initializing the reading interface to read from //stdin and write to stdout var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); //Asking for user input and providing a callback to deal with the user input rl.question("What is your name? ", function(answer){ console.log("Your name is: " + answer); console.log("Press Ctrl+C to end the program"); });
The output would be:
G:\node\testapp>node input.js What is your name? Mohamed Your name is: Mohamed Press Ctrl+C to end the program
Connecting to MongoDB in Node.js
Lets now see how to connect to MongoDB from Node.js. As with reading user input, for MongoDB as well we have a Node.js module called mongodb
. But this module would have to be downloaded using NPM (Node Package Manager). The mongodb module provides the driver to connect to MongoDB DB from Javascript. To install the mongodb module using NPM run the following command from your command prompt: npm install mongodb
.
Note: NPM comes with the Node.js installation and you need not do anything additional to install NPM.
The below code shows how to connect to MongoDB and fetch records from a collection which already had few records populated. Getting familiarity with the MongoDB commands is required. You can find a very detailed documentation on MongoDB here.
//FileName: mongodb.js //Importing the required mongodb driver var MongoClient = require('mongodb').MongoClient; //MongoDB connection URL var dbHost = 'mongodb://localhost:27017/test'; //Name of the collection var myCollection = "people"; //Connecting to the Mongodb instance. //Make sure your mongodb daemon mongod is running on port 27017 on localhost MongoClient.connect(dbHost, function(err, db){ if ( err ) throw err; //Query Mongodb and iterate through the results db.collection(myCollection).find({},{},{}).toArray( function(err, docs){ for(index in docs){ console.log(docs[index]); } } ); });
Now that we have seen how to accept user input and how to connect to MongoDB, I will next show how to perform CRUD operations using our Book example.
CRUD Operations
We would take the data to be inserted into the DB via the command line and also the choice of operation to be performed i.e whether to Create OR Read OR Update OR Delete. The below code shows how the menu is printed and accepts the user choice for the operation.
var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); //The below code prints the menu var printMenu = function(db){ console.log("Welcome to CRUD demo using Node.js and MongoDB"); console.log("1. Insert a new Book"); console.log("2. List all the books"); console.log("3. Update the book by ISBN"); console.log("4. Delete the book by ISBN"); console.log("5. Quit"); rl.question("Enter your choice: ", function(answer){ console.log("Choice entered is: " + answer); switch(answer){ case "1": insertBook(dbConn); break; case "2": listBooks(dbConn); break; case "3": updateBook(dbConn); break; case "4": deleteBook(dbConn); break; case "5": console.log("Press Ctrl+C to exit the program"); return; } }); }
Inserting record into MongoDB in Node.js
Inserting a new record involves taking user input i.e name of the book, isbn of the book, authors and page count. After this we use the MongoDB API to execute the insert statement. The below code is the method to insert a new document.
var insertBook = function(db){ rl.question("Enter the name of the book: ", function(bookName){ rl.question("Enter the ISBN of the book: ", function(isbn){ rl.question("Enter the authors of the book[Comma separated if more than 1]: ", function(author){ rl.question("Enter the total number of pages: ", function(pageCount){ db.collection(myCollection).find({isbn: isbn},{},{}).toArray( function(err, docs){ if ( docs.length > 0){ console.log("Book with ISBN " + isbn + " already exists"); printMenu(dbConn); }else{ db.collection(myCollection).insert({ 'name':bookName, 'isbn': isbn, 'author': author, 'pages': pageCount }, bookInsertHandler); } } ); }); }); }); }); }
Listing/Reading records from MongoDB in Node.js
The MongoDB API provides find
method to retrieve the results from the DB. The find
method accepts three parameters namely: the query clause, the project clause i.e which attributes from the collection to be retrieved and the sort clause. The below code fetches and displays the result:
var listBooks = function(db){ db.collection(myCollection).find({},{},{}).toArray( function(err, docs){ for(index in docs){ console.log(docs[index]); } printMenu(dbConn); } ); }
Updating records in MongoDB in Node.js
To update the book we need to take ISBN number to retrieve the book and update its data. Also we take user input for the newer data and accordingly use the MongoDB API to update the record. The below code updates the record:
var updateBook = function(db){ rl.question("Enter the ISBN of the book you want to update: ", function(answer){ db.collection(myCollection).find({isbn: answer},{},{}).toArray( function(err, docs){ if ( docs.length == 0){ console.log("Book with ISBN " + isbn + " not found"); printMenu(dbConn); }else{ rl.question("Enter the name of the book: ", function(bookName){ rl.question("Enter the authors of the book[Comma separated if more than 1]: ", function(author){ rl.question("Enter the total number of pages: ", function(pageCount){ db.collection(myCollection).update({"isbn":answer}, { 'name':bookName, 'author': author, 'pages': pageCount, 'isbn':answer }, bookUpdateHandler); }); }); }); } }); }); }
Deleting records from MongoDB in Node.js
To delete the record we take the ISBN number for the book and use the MongoDB API to delete the record. The below code does the operation.
var deleteBook = function(db){ rl.question("Enter the ISBN of the book you want to update: ", function(answer){ db.collection(myCollection).find({isbn: answer},{},{}).toArray( function(err, docs){ if ( docs.length == 0){ console.log("Book with ISBN " + answer + " not found"); printMenu(dbConn); }else{ db.collection(myCollection).remove({"isbn":answer}, bookDeleteHandler); } }); }); }
Node.js + MongoDB Example
The complete sample program to demonstrate CRUD operations in Nodde.js and MongoDB integration example is given below.
//Filename: crud.js var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var MongoClient = require('mongodb').MongoClient; var dbHost = 'mongodb://localhost:27017/test'; var myCollection = "crud"; var dbConn; var bookInsertHandler = function(err, recs){ if(err) throw err; console.log("Successfully inserted the book into database"); printMenu(dbConn); } var bookUpdateHandler = function(err, recs){ if(err) throw err; console.log("Successfully updated the book"); printMenu(dbConn); } var bookDeleteHandler = function(err, recs){ if(err) throw err; console.log("Successfully deleted the book"); printMenu(dbConn); } var printMenu = function(db){ console.log("Welcome to CRUD demo using Node.js and MongoDB"); console.log("1. Insert a new Book"); console.log("2. List all the books"); console.log("3. Update the book by ISBN"); console.log("4. Delete the book by ISBN"); console.log("5. Quit"); rl.question("Enter your choice: ", function(answer){ console.log("Choice entered is: " + answer); switch(answer){ case "1": insertBook(dbConn); break; case "2": listBooks(dbConn); break; case "3": updateBook(dbConn); break; case "4": deleteBook(dbConn); break; case "5": console.log("Press Ctrl+C to exit the program"); return; } }) } var insertBook = function(db){ rl.question("Enter the name of the book: ", function(bookName){ rl.question("Enter the ISBN of the book: ", function(isbn){ rl.question("Enter the authors of the book[Comma separated if more than 1]: ", function(author){ rl.question("Enter the total number of pages: ", function(pageCount){ db.collection(myCollection).find({isbn: isbn},{},{}).toArray( function(err, docs){ if ( docs.length > 0){ console.log("Book with ISBN " + isbn + " already exists"); printMenu(dbConn); }else{ db.collection(myCollection).insert({ 'name':bookName, 'isbn': isbn, 'author': author, 'pages': pageCount }, bookInsertHandler); } } ); }); }); }); }); } var listBooks = function(db){ db.collection(myCollection).find({},{},{}).toArray( function(err, docs){ for(index in docs){ console.log(docs[index]); } printMenu(dbConn); } ); } var updateBook = function(db){ rl.question("Enter the ISBN of the book you want to update: ", function(answer){ db.collection(myCollection).find({isbn: answer},{},{}).toArray( function(err, docs){ if ( docs.length == 0){ console.log("Book with ISBN " + isbn + " not found"); printMenu(dbConn); }else{ rl.question("Enter the name of the book: ", function(bookName){ rl.question("Enter the authors of the book[Comma separated if more than 1]: ", function(author){ rl.question("Enter the total number of pages: ", function(pageCount){ db.collection(myCollection).update({"isbn":answer}, { 'name':bookName, 'author': author, 'pages': pageCount, 'isbn':answer }, bookUpdateHandler); }); }); }); } }); }); } var deleteBook = function(db){ rl.question("Enter the ISBN of the book you want to update: ", function(answer){ db.collection(myCollection).find({isbn: answer},{},{}).toArray( function(err, docs){ if ( docs.length == 0){ console.log("Book with ISBN " + answer + " not found"); printMenu(dbConn); }else{ db.collection(myCollection).remove({"isbn":answer}, bookDeleteHandler); } }); }); } MongoClient.connect(dbHost, function(err, db){ if ( err ) throw err; dbConn = db; printMenu(); });
To run the above code use the following command: node crud.js
Summary
This tutorial walks you through how to write a simple CRUD operations with the combination of Node.js and MongoDB technologies. These two are using JSON as the data format that makes it to fit together perfectly. I hope you would have got good idea on how to create, read, update and delete a record in MongoDB using Node.js script. If you have any questions, please write it in the comments section. In my next article, I will write about MongoDB with Mongoose API.