Over a million developers have joined DZone.

Performing CRUD Operations on MongoDB in a Node.js Application Using MongoDB Driver

DZone's Guide to

Performing CRUD Operations on MongoDB in a Node.js Application Using MongoDB Driver

· Database Zone
Free Resource

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

A NoSQL database is the go-to choice while writing applications using Node.js. In particular, MongoDB has got a lot of popularity in the community. Thanks to the awesome MEAN (MongoDB-Express-Angular-Node) stack, that makes everyone realize that an entire web app can be written using just one language (JavaScript).

There are a number of drivers created by the community to interact with MongoDB from a Node.js app. The official mongodb driver seems to be the simplest of them. Because, the JavaScript API it provides to interact with MongoDB is quite similar to the way one talks to MongoDB from console. In this post, we will learn to perform simple CRUD operations on a MongoDB document store using the mongodb driver.

We will be dealing with a set of students that is initially loaded with the following data:

 "studentId" : 1,
 "class" : 8,
 "name" : "Ravi",
 "marks" : [
  { "totalMarks" : 500, "percent" : 83.3 },
  { "totalMarks" : 510, "percent" : 85 } ],
 "studentId" : 2,
 "name" : "Rupa",
 "class" : 8,
 "marks" : [
  { "totalMarks" : 570, "percent" : 95 },
  { "totalMarks" : 576, "percent" : 96 } ]

To be able to work with the above data, we need to establish a connection with MongoDB first. Before that, we need to get the driver installed in the current project. Following command will install the driver when it is ran in the folder where the target Node.js project is located:

npm install mongodb

I prefer placing the code interacting with MongoDB in a separate file. As first thing, we need to get a reference to the MongoDB client and establish a connection:

var mongoClient=require('mongodb').MongoClient;
var mongoDbObj;

mongoClient.connect('mongodb://localhost/studentDb', function(err, db){
    console.log("Connected to MongoDB");
    mongoDbObj={db: db,
      students: db.collection('students')

Retrieving values:

In the above connection URL, studentDb is name of the database. If the database doesn’t already exists, it is created automatically. I cached the students collection in the mongoDbObj object to avoid calling collections() over and over. Following statement fetches all students from the database:

mongoDbObj.students.find().toArray(function(err, data){
    //operate with the deta

The find() method returns the objects in the form of documents. We need to convert the data obtained to a JavaScript array to operate with it easily. This is done by the toArray method.

Following are some examples showing using find with conditions:

mongoDbObj.students.find({studentId:1})    //Fetches the student with value of studentId 1
mongoDbObj.students.find({studentId:{$gte:2}})    //Fetches the student with value of studentId greater than or equal to 2
mongoDbObj.students.find({"marks.totalMarks":500})    //Fetches the student with at least one of the values of totalMarks 500
mongoDbObj.students.find({"marks.totalMarks":{$lte:500}})    //Fetches the student with at least one of the values of totalMarks less than or equal to 500

Inserting data:

Inserting data is a straight forward operation. It needs the object to be inserted, an optional options object and a callback to handle the success or failure.

mongoDbObj.students.insert(newStudent,{w:1},function(err, result){
    //Handle the failure case
    //Handle the success case

The value of options object passed in above call to insert method is used to get acknowledgement of write operations.

Updating data:

Following statement replaces the matched object:

mongoDbObj.students.update({studentId:1},{name:”Ravi Kiran”},{w:1}, function(err, result){
    //Handle success and failure

The issue with the above approach is, as it does a full replace, there is a possibility of losing data of other fields in the matched record. Following statement updates the specified fields leaving unspecified fields untouched:

mongoDbObj.students.update({studentId:1},{$set: {name:”Ravi Kiran”}},{w:1}, function(err, result){
  //Handle success and failure

Deleting data:

Calling remove() method without any conditions deletes all records in a collection:

mongoDbObj.students.remove(function(err, result){
    //Handle success and failure

If a condition is passed in, it deletes the records that match the criteria:

mongoDbObj.students.remove({studentId:studentId},{w:1},function(err, result){
    //Handle success and failure

We will discuss more about MongoDB and Node.js in future posts.

Happy Coding!

It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate

mongodb ,node.js

Published at DZone with permission of Rabi (ravi) Kiran, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}