Search

How to Create MongoDB Database in Node.js

MongoDB is an open-source platform written in C++. It is a document database designed for ease of development and scaling. It is a cross-platform, document-oriented and non-structured database. This article is a quick guide on how to create MongoDB database in Node.js. We will understand MongoDB compatibility and language compatibility and exploreMongo shell. We will see how to import data into the database, how to use MongoDB driver for node.js and the Node.js based CRUD operations. We will conclude with building a simple app using node express app with MongoDB to store and serve content. How MongoDB is different from relational databases Relational databases are SQL enabled and are organised in tables with each entry containing a specific set of columns with a specific data type.  It is seen that sometimes relational databases become very complex for simple schemas, for e.g., where an employee who has more than one phone number, email IDs, addresses, teams, etc. and all the related data is stored in different tables. To retrieve complete information for an employee, multiple tables needs to be joined and queried.  One of the disadvantages with relational databases is that to update or change schema, we would need to modify multiple tables. As the requirement changes, more updates might be needed, further complicating the design. This makes it necessary for a dedicated DB admin. Mongo is a NoSql DB and is object-based containing an entire entity in document record. Unlike relational database, NoSqldb can be queried faster and easy to get complete details of a specific entity or document.  Another feature of Mongo is if there is no document matching to query than no error is returned. In relational database, a table contains the same set of fields whereas in Mongo DB, schema is dynamic and each one need not conform to the same schema.Mongo is developer friendly and JSON representation makes it easy to parse. MongoDB stores documents in collections. Collections are analogous to tables in relational databases. In MongoDB, databases hold collections of documents. In addition to collections, MongoDB supports: Read-only Views (Starting in MongoDB 3.4) On-Demand Materialized Views (Starting in MongoDB 4.2). MongoDB data structure Documents – JSON Objects Store data as BSON (Binary JSON) [For the BSON spec, see bsonspec.org] The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. For example, the following document contains values of varying types var mydoc = {_id: ObjectId("3423jksdhfi83p9fj90cd"),  name: { firstName: "Sachin", lastName: "Tendulkar" },  birth: new Date('Apr 24, 1973'),  awards:[ “Bharat Ratna”, “Padma Vibhushan”, “Padma Shri”]  followers :NumberLong(30000000)  } _id holds an ObjectId,  name holds an embedded document that contains firstName and lastName, birth hold values of Date types awards holds an array of strings followers holds a value of NumberLong type. Note: Mongo supports nesting up to 100 levels. Learn more about bson-types at https://docs.MongoDB.com/manual/reference/bson-types/ Setup MongoDB environmentFormacOS platform, download the tgz file and extract the file. Easiest way to get the items in your path is to copy them to usr/local/bin directory. Follow the below steps to get it doneNow type ‘mongod’ in command prompt which is mongo daemon and  you can see it has started. Invoke another command prompt and type ‘mongo’ to start off in the shell. To make sure everything is working let’s insert a dummy data and observe that it inserted one document. db.users.insert({“name”: “Sachin Tendulkar”})Database is all setup. For Windows platform, download the msi and run the installation to complete the installation. Once the installation is done, you can find where it has been installed. Two things important in bin folder are mongo and MongoD. Copy the path and add to the path in environment variables.  Once this has been done, we should be able to run both the Mongo Server and Mongo Shell from command prompt.  Invoke the command prompt and do ‘md \data’ and then create data DB by ‘md \data\db’. This is the file that mongo is going to look for to use to store information about database.  Now type ‘mongoD’ in command prompt which is mongo daemon and  you can see it has started. Invoke another command prompt and type ‘mongo’ to start off in the shell. To make sure everything is working let’sinsert a dummy data and observe that it inserted one document. db.users.insert({“name”: “Sachin Tendulkar”}) Database is all setup. The recommended way to get started using the Node.js driver is by using NPM (Node Package Manager) to install the dependency in your project. After you’ve created your project with npminit, you can install the MongoDB driver and its dependencies with the command: npm install MongoDB --save This will download the MongoDB driver and add a dependency entry in your package.json file. We will learn more of this as we go forward. Compatibility MongoDB compatibility Note: The driver does not support older versions of MongoDBNode.js DriverMongoDB 4.2MongoDB 4.0MongoDB 3.6MongoDB 3.4MongoDB 3.2MongoDB 3.0MongoDB 2.6>= 3.X✓✓✓✓✓✓✓>= 3.2.1✓✓✓✓✓✓>= 3.1✓✓✓✓✓✓>= 3.0✓✓✓✓✓>=2.2.12✓✓✓✓Language compatibilityNode.jsDriverNode.js v0.8.XNode.js v0.10.XNode.js v0.12.XNode.js v4.X.XNode.js v6.X.XNode.js v8.X.XNode.js v10.x.xNode.js v12.x.x>=3.X.X✓✓✓✓✓2.2.X – 2.0.X✓✓✓✓✓✓>=1.4.18✓✓✓1.4.x✓✓Few salient points When designing the schema for your database, a quick understanding of Embedded vs References is helpful. You can refer Coderwall for more information on this.  Three of the other features that mongo provides: Indexing, Sharding and replicationcan make Mongo the right choice for your application. Indexing- supports ad hoc queries 64 indices per collection Single Field Compound (multiple Fields) Unique Sharding  - Scalability Partitions data onto different machines Scale application into smaller systems Autosharding supported by Mongo Challenging to set upReplicationReliability (Primary and n number of secondary server) Maximizes uptime Replica sets Automatic failoverExplore Mongo Shell Note:All the examples and snaps are taken in macOS. Invoke terminal and type ‘mongod’ which will display the listening port 27017Sinncewe are running locally, we need not secure and optimize it Invoke another terminal (command + T) and type ‘mongo’You should see that we are now connected to MongoDB://127.0.0.1:27017 By default, we are connected to test database  Type ‘db’ to check it in terminal and observe ‘test’ Let us use a different database say ‘MyNewMongoDB’ Type ‘use MyNewMongoDB’ Output: Switched to dbMyNewMongoDB To view all available dbs, type ‘show dbs’.Note: We will not see the new db ‘MyNewMongoDB’. Instead the db is created when the first document is created. Mongo stores data in databases which are separated into collections of documents. To Create a new collection, we need to insert a document and the collection will be created as a side effect. Type ‘db.cricketers.insert({“name”:”Sachin”}) Now check ‘show dbs’ to view our new db Type ‘show collections’ to check that our collection is created.As you can see, mongo doesn’t require any schema or setup work to start working with data. The commands we used are very similar to what we have in SQL but mongo shell uses a JavaScript interpreter. So, we can interact with database using JavaScript expressions making it easy to perform various tasks. Print(‘test’) will print test var arr = [“one”, “two”, “three”] type arrwhich will print the results. Let us take this option to explore further i.e. we will insert 1000 records to db using a for loop.for(i=0;i<1000;i++){ db.numbers.insert({"number":i}) } Though it says there was only one insert, it’s counting the number of operations and not individual documents. This is evident from the command ‘db.numbers.count()’ Now let’s try to find a single document from the database and understand the query better. Type ‘db.numbers.find({"number": 2})’ and this should display the one record. Let’s ask the mongo to explain it for us by adding the explain command.db.numbers.find({“number”:”2”}).explain() Explain did mentioned about the query planner but didn’t give much information about the execution. So, let’s pass execution status to get that information. db.numbers.find({“number”:”2”}).explain(“executionStats”)Now we can see that it ran through 999 records and took 0 milliseconds. May be if we increase the count to 1 million we can find higher time in executionTime. Since we don’t want to run through all the records, let’s create a simple index to see how the outcome changes. db.numbers.createIndex({number: 2}) Here it is similar to find but the number is a special variable and it is not a string. Now, let us try execution status again and see the result.As we can see, only one document is examined and imagine if we want to search in a collection of 10 million or more records. It makes a huge difference. Import data into the database: Though inserting data into mongo using shell or language driver is handy. Most of the time we have the data in some form which we need to import to our database. And Mongoimport command can import the data in json, csv or tsv formats and no custom code needed.In our case, we are using random data generated using. Sample view of the data downloaded:‘mongoimport –help’ will display the options available. Namespace options display the db and the collection to which the data has to be imported. Input options is next section in which we will use the file option. Json format is default one here. However, the file being imported is an array and not an object so we need to dash dash json array flag as well. Invoke the terminal and make sure we are in the file directory where the json file resides or downloaded.As we can see, we have imported 7 documents successfully.  Now let us check if mongo has the data what we wanted Switch to mongo client and type ‘use MyNewMongoDB’ Type ‘show collections’ to view the collections now having persons. We can count records using commanddb.persons.count() or find using db.persons.find({“isActive”: true}). Mongo shell CRUD operations Now that we have the data in place, let’s explore the standard CRUD operations in database.If client is not running, start it by typing mongo in terminal and switch to newly created database ‘MyNewMongoDB’ [READ] In the available data,let’s find out the number of persons having eyecolor blue. GET: db.persons.find({“eyecolor”: “blue”}).count() This should result in count of 2 records. [CREATE] Now let’s go and add one more person with eyecolor blue. (INSERT) Insert is going to be little complex and might span across lines based on the data we insert.  db.persons.insert({ "_id": "5eee4d58c952ec90ad43dfe8", "index": 7, "guid": "fbc2510e-678f-4843-b612-96b899ee5e9b", "isActive": true, "balance": "$3,996.47", "picture": "http://placehold.it/32x32", "age": 18, "eyeColor": "blue", "name": "SteuPoluard", "gender": "female", "company": "EXTRAWEAR"}) Note: In the above case, it is spanning multiple lines and Mongo is not going to execute/process until the last parenthesis isclosed and also _id is unique. Output should display one new record is inserted. WriteResult({ "nInserted" : 1 }) If we try to find the people with eye color blue, we should get 3 records.UPDATE] Now let’s go and update the inserted record with an email Id. Updates can happen to replace the entire document or a sub-set of the data. We wanted to add the email id without losing the entire object.For this we need to use the set functionality.db.persons.update({"name":"SteuPoluard"},  ... {$set: {"email":"Steu.Poluard@extrawear.com"}}) Output: WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Now if we find the record to check if email is been added.Now if we want to update the tags then we need to use a different operator called $addToSet. db.persons.update({"name":"Sara Pollard"},  ... {  ... $addToSet: {"tags":"newtag"}  ... })Note: There is a large set of update operators are available, refer to mongo site to explore this functionality in depth. [DELETE] Now lets finally delete the record added with name – ‘SteuPoluard’ db.persons.remove({"name":"SteuPoluard"}) To verify, let’s see if find command finds it. db.persons.find({"name":"SteuPoluard"}) No result. So, the record got successfully deleted. Say if we want to delete the collection itself. db.persons.drop() Check show collections to find the persons collection is no more.Using MongoDBdriver for node.js Now let’s write some code in node.js to interact with the database. The drivers for all of the languages work similarly so once we have it working for node. Other language drivers should be pretty much same. The official MongoDB Node.js driver provides both callback-based and Promise-based interaction with MongoDB, allowing applications to take full advantage of the new features in ES6. The 2.x series of the driver is powered by a brand-new core driver and BSON library. To understand more about the changes made from drive 1.x to 2.x, refer to thisblog. First step is to make sure our Mongo server is up and running with db ‘MyNewMongoDB’ and the imported data collection i.e. person already in place. Note: In case if the collection is dropped, please follow the above steps to create and import the dataSteps:Create an index.js file  Setup the mongo client using MongoDB package. var MongoClient = require('MongoDB').MongoClient; Url for the database uses the MongoDB protocol and connects to the specified server. var url = 'MongoDB://localhost:27017/MyNewMongoDB'; Finally, we want to connect to the MongoClient and in the callback we log the connection is made successfullyvarMongoClient = require('MongoDB').MongoClient;  varurl = 'MongoDB://localhost:27017/MyNewMongoDB';  MongoClient.connect(url, function(err, db) {  console.log("Connected successfully to server");  db.close();  }) Invoke a terminal and navigate to the index.js file folder. Type node index.js and observe that ‘Connected successfully to server’ Note: If you are facing any error, check if MongoDB server is running and npm install is performed. Now, let’s go ahead and try to access all the documents or specific document and print them in console. Since we have already made the connection. Let’s find the record in the callback of the connection. varMongoClient = require('MongoDB').MongoClient;  // Server is running locally on the default port and db is name is 'MyNewMongoDB'  varurl = 'MongoDB://localhost:27017/MyNewMongoDB';  varfindDocuments = function(db, callback) {  // collection name is 'persons' which is imported  varcollection = db.collection('persons');  // looking for a document with field 'name' and value 'Sara Pollard'  collection.find({"name":"Sara Pollard"}).toArray(function(err, docs) {  console.log(docs);  callback();      })  }  MongoClient.connect(url, function(err, db) {  console.log("Connected successfully to server");  // On obtaining the connection, find the record and close the db connection.  findDocuments(db, function () {  db.close();      })  }) Type node index.js to check if the record is obtained successfully and is logged.As we can see, the same interfaces covered in the mongoShell work here as well for all CRUD operations. For sake of review, here is the list Create --> insert. Read --> find or findOne. Update --> update. Delete --> delete. Node.js based CRUD operations Let ussetup up a simple application using Node.js and MongoDB. We would understand how to setup the driver and perform simple CRUD operations. Follow the below steps to setup project mkdirlearnMongoDB cd learnMongoDB npminit [you would be prompted for inputs related to package.json] npm install MongoDB–save [--save is to update the package.json] Assuming that the mongo db server is still running. If not, start as mentioned earlier. Open the directory learnMongoDB in your favourite IDE. (I am using Visual Studio code). Add a file app.js with the below snippet of code. // import the MongoDB and get the client object.  constMongoClient = require('MongoDB').MongoClient;  constassert = require('assert');  // Connection URL - can be obtained in the MongoDB server  consturl = 'MongoDB://localhost:27017';  // Database Name   constdbName = 'myproject';  // Create a new MongoClient  constclient = newMongoClient(url);  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  client.close();  }); Observe that we are not providing the db name in the URL. Instead we are getting the db instance on successfully connecting to the server. This way, we can get connected to different databases in the same client instances. Note: We are using assert module to check if connection is successful or not by validating the error object. Will be used for other CRUD operations as well. Run ‘node app.js’ and should observe the log mentioning connected successfully to server. Insertion: Now we have the db object, let’s get hold of the collection and insert some objects into it. Create a function ‘insertDocuments’ to perform insertion into the collection.Call this insertDocuments in the callback of successful connection. // insertDocuments take the db instance  constinsertDocuments = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Insert some documents  collection.insertMany([        {a :1}, {a :2}, {a :3}      ], function(err, result) {  assert.equal(err, null); // assertion to check if any error is there.  assert.equal(3, result.result.n);  assert.equal(3, result.ops.length);  console.log("Inserted 3 documents into the collection");  callback(result); // return the inserted documents      });  }  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  console.log(result);  client.close();    })  }); In the callback of the insertDocuments, we get the result object which is as shown below: { result: { ok: 1, n: 3 }, ops: [ { a: 1, _id: 5eeefd2a16f61641f58a9418 },  { a: 2, _id: 5eeefd2a16f61641f58a9419 },  { a: 3, _id: 5eeefd2a16f61641f58a941a } ],  insertedCount: 3,  insertedIds:  { '0': 5eeefd2a16f61641f58a9418,  '1': 5eeefd2a16f61641f58a9419,  '2': 5eeefd2a16f61641f58a941a } } As you can see, result object gives an overview of the action. Ops is the objects added to the collection. And other fields are self-explanatory. Note: You might have noticed that a new field ‘_id’ has been added which is generated by MongoDB for unique identification. If we are not happy with the unique id, we can as well supply like we did during importing of the data. Find: Let’s check if documents added can be retrieved using find. Collection object has a method called ‘find’ which take a parameter i.e. search query to identify the objects. If it is empty then all documents are returned.Invoke the findDouments in the callback of insertion for validating the records inserted. We can use a query filter to get specific item as well. // findDocuments from the db instance  constfindDocuments = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Finds all documents. If required, parameterize the query filter to get specific items.  collection.find({}).toArray(function(err, docs) {  assert.equal(err, null);  console.log("Found the following records");  console.log(docs)  callback(docs);      });    }  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  findDocuments(db, function() {  client.close();      })        })  }); For example, if we want to find a specific set of documents based on pre-defined query filter like ‘{‘a’:3}’ : // Find specific document with a query filter  constfindDocuments = function(db, callback) {  // Get the documents collection  const collection = db.collection('documents');  // Find some documents  collection.find({'a': 3}).toArray(function(err, docs) {  assert.equal(err, null);  console.log("Found the following record(s)");      console.log(docs);  callback(docs);    });  } Updation: Now go andupdate a specific document. There are various methods available for updation like update, updateMany, updateOne etc. Use updateOne method to update the first one which matches the query. Signature: updateOne(filter, update, options, callback) Let’s send the filter as {a : 2 } i.e. document whose field a is equal to 2, update as $set: {b:1} to avoid replacement of entire object i.e. adding a new field b to document with value set as 1. Ignore options which is an optional and have a callback to capture post actions. constupdateDocument = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Update document where a is 2, set b equal to 1  collection.updateOne({ a :2 }        , { $set: { b :1 } }, function(err, result) {  assert.equal(err, null);  assert.equal(1, result.result.n);  console.log("Updated the document with the field a equal to 2");  callback(result);      });      }    // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  findDocuments(db, function() {  updateDocument(db, function() {  client.close();          })      })       })  }); Deletion: Let’s use deleteOne method to find and delete the first item with field a and value 3. constremoveDocument = function(db, callback) {  // Get the documents collection  constcollection = db.collection('documents');  // Delete document where a is 3  collection.deleteOne({ a :3 }, function(err, result) {  assert.equal(err, null);  assert.equal(1, result.result.n);  console.log("Removed the document with the field a equal to 3");  callback(result);      });        }  // Use connect method to connect to the Server  client.connect(function(err) {  assert.equal(null, err);  console.log("Connected successfully to server");  constdb = client.db(dbName);  //insert the documents and in the callback, close the client.  insertDocuments(db, function(result) {  findDocuments(db, function() {  updateDocument(db, function() {  removeDocument(db, function(){  client.close();              })          })      })    })  }); Note: All the methods on the collection returns promise object if callback is not passed. So to avoid callback hell as we see above, we can rely on promise and program the code better. Node express app with MongoDB to store and serve content Now that we have fair idea of how to work with MongoDB using mongoshell and node.js driver. Let us build a simple app using node express app with MongoDB to store and serve content. Note: Since this topic is more about MongoDB rather than express, we will keep the express app a basic version. Let us go and comment out all the code in the app.js file from the previous example. We should be left with this: // import the MongoDB and get the client object.  constMongoClient = require('MongoDB').MongoClient;  const { equal } = require('assert');  // Connection URL - can be obtained in the MongoDB server  consturl = 'MongoDB://localhost:27017';  // Database Name   constdbName = 'myproject'; Invoke a terminal and navigate to the directory where the app.js file is located. Let us install express with the below command. npm install express –save Import the express and body-parser as shown below: constexpress = require('express');  constbodyParser = require('body-parser');  create an app instance and use bodyParser.json().  constapp = express();  app.use(bodyParser.json());  Let the express app be listening on port 3000 with a default route.  app.get('/', (req, res) =>res.send('Express app with MongoDB!'));  app.listen(3000, () =>console.log("App listening at http://localhost:3000")); Consolidated code: constexpress = require('express');  constbodyParser = require('body-parser');  // import the MongoDB and get the client object.  constMongoClient = require('MongoDB').MongoClient;  const { equal } = require('assert');  // Connection URL - can be obtained in the MongoDB server  consturl = 'MongoDB://localhost:27017';  // Database Name   constdbName = 'myproject';  constapp = express();  app.use(bodyParser.json());  app.get('/', (req, res) =>res.send('Express app with MongoDB!'));  app.listen(3000, () =>console.log("App listening at http://localhost:3000")); In the terminal, run ‘node app.js’ and should see the console log that app is listening in port 3000. To check the default route is working correctly. Invoke the postman and perform get operation.Now let us create a new route to retrieve the document based on field a and parameterized value. app.get('/api/documents/:name', (req,res) => {  }) :name is the parameter being passed. So let’s retrieve it from request parameters. And since we know it is numeric and not string. Let’s parse it to integer. constname = parseInt(req.params.name); Now lets connect to the MongoClient as earlier. This time we will not be using callback approach rather rely on the promise being returned. constclient = awaitMongoClient.connect(url, {useNewUrlParser:true});Since returned object is a promise and in order for the promise to be resolved or rejected. We need to use await keyword before proceeding further. Note: Promise object has two properties i.e. state and result. Promise state property initially has ‘pending’ and post execution will be either ‘fulfilled’(resolve) or ‘rejected’(reject). Similarly, result will be ‘undefined’ initially and then changes to ‘value’[resolve(value)] or ‘error’[reject(error)]. Let us get the db ‘myproject’ and find the first document based on the query filter from collection using findOne method. constdb = client.db(dbName);  constdocument = awaitdb.collection('documents').findOne({"a":name}); Once we get the document, lets return the status as 200 with the obtained document and close the client connection. res.status(200).json(document);  client.close(); As we are using await keyword, we need to add async keyword to the callback. And also lets add a try-catch block to return an error status in case of connection failure as internal server error. app.get('/api/documents/:name',async (req,res) => {  try {     constname = parseInt(req.params.name);  constclient = awaitMongoClient.connect(url, {useNewUrlParser:true});  constdb = client.db(dbName);  constdocument = awaitdb.collection('documents').findOne({"a":name});  res.status(200).json(document);  client.close();            } catch(error) {  res.status(500).json({message:"Error connecting to db", error});      }  }) Now we are good to go and restart our express app. Press ctrl + c and run node app.js to see app is listening at. Make sure that MongoDB Server is up and running in the background. Switch to postman and perform a GET operation. This should return the first record in the collection as shown below. {"_id":"5eeefd2a16f61641f58a9419","a":2,"b":1} Same GET request can be performed for other documents by changing the name as 2Similar to get operations, we can configure the routes to perform other CRUD operations on MongoDB to store and serve the content.  Conclusion In this guide, we have gone overMongoDB compatibility and language compatibility and explored the Mongo shell. We have seen how to import data into the database, how to use MongoDB driver and the Node.js based CRUD operations. We have also looked at how to build a simple app using node express app with MongoDB to store and serve content.Armed with this knowledge, you are ready to take a deeper dive into MongoDB and NodeJS. Here’s wishing you the best! Real coding requires real exercises. Practice live coding with our programming  experts on live workshops now.

How to Create MongoDB Database in Node.js

7K
How to Create MongoDB Database in Node.js

MongoDB is an open-source platform written in C++. It is a document database designed for ease of development and scaling. It is a cross-platform, document-oriented and non-structured database. 

This article is a quick guide on how to create MongoDB database in Node.js. We will understand MongoDB compatibility and language compatibility and exploreMongo shell. We will see how to import data into the database, how to use MongoDB driver for node.js and the Node.js based CRUD operations. We will conclude with building a simple app using node express app with MongoDB to store and serve content. 

How MongoDB is different from relational databases 

Relational databases are SQL enabled and are organised in tables with each entry containing a specific set of columns with a specific data type.  

It is seen that sometimes relational databases become very complex for simple schemas, for e.g., where an employee who has more than one phone number, email IDs, addresses, teams, etc. and all the related data is stored in different tables. To retrieve complete information for an employee, multiple tables needs to be joined and queried.  

One of the disadvantages with relational databases is that to update or change schema, we would need to modify multiple tables. As the requirement changes, more updates might be needed, further complicating the design. This makes it necessary for a dedicated DB admin. 

Mongo is a NoSql DB and is object-based containing an entire entity in document record. Unlike relational database, NoSqldb can be queried faster and easy to get complete details of a specific entity or document.  

Another feature of Mongo is if there is no document matching to query than no error is returned. In relational database, a table contains the same set of fields whereas in Mongo DB, schema is dynamic and each one need not conform to the same schema.Mongo is developer friendly and JSON representation makes it easy to parse. 

MongoDB stores documents in collections. Collections are analogous to tables in relational databases. In MongoDB, databases hold collections of documents. 

In addition to collections, MongoDB supports: 

  • Read-only Views (Starting in MongoDB 3.4) 
  • On-Demand Materialized Views (Starting in MongoDB 4.2). 

MongoDB data structure 

  • Documents – JSON Objects 
  • Store data as BSON (Binary JSON) [For the BSON spec, see bsonspec.org] 

The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. For example, the following document contains values of varying types 

var mydoc = {_id: ObjectId("3423jksdhfi83p9fj90cd"), 
name: { firstName: "Sachin", lastName: "Tendulkar" }, 
birth: new Date('Apr 24, 1973'), 
awards:[ “Bharat Ratna”, “Padma Vibhushan”, “Padma Shri”] 
followers :NumberLong(30000000) 
} 
  • _id holds an ObjectId,  
  • name holds an embedded document that contains firstName and lastName, 
  • birth hold values of Date types 
  • awards holds an array of strings 
  • followers holds a value of NumberLong type. 

Note: Mongo supports nesting up to 100 levels. 

Learn more about bson-types at https://docs.MongoDB.com/manual/reference/bson-types/ 

Setup MongoDB environment

FormacOS platform, download the tgz file and extract the file. Easiest way to get the items in your path is to copy them to usr/local/bin directory. Follow the below steps to get it done

How to Create MongoDB Database in Node.js

Now type ‘mongod’ in command prompt which is mongo daemon and  you can see it has started. Invoke another command prompt and type ‘mongo’ to start off in the shell. To make sure everything is working let’s insert a dummy data and observe that it inserted one document. 

db.users.insert({“name”: “Sachin Tendulkar”})

How to Create MongoDB Database in Node.js

Database is all setup. 

For Windows platform, download the msi and run the installation to complete the installation. Once the installation is done, you can find where it has been installed. Two things important in bin folder are mongo and MongoD. Copy the path and add to the path in environment variables.  

Once this has been done, we should be able to run both the Mongo Server and Mongo Shell from command prompt.  

Invoke the command prompt and do ‘md \data’ and then create data DB by ‘md \data\db’. This is the file that mongo is going to look for to use to store information about database.  

Now type ‘mongoD’ in command prompt which is mongo daemon and  you can see it has started. Invoke another command prompt and type ‘mongo’ to start off in the shell. To make sure everything is working let’sinsert a dummy data and observe that it inserted one document. 

db.users.insert({“name”: “Sachin Tendulkar”}) 

Database is all setup. 

The recommended way to get started using the Node.js driver is by using NPM (Node Package Manager) to install the dependency in your project. 

After you’ve created your project with npminit, you can install the MongoDB driver and its dependencies with the command: 

npm install MongoDB --save 

This will download the MongoDB driver and add a dependency entry in your package.json file. 

We will learn more of this as we go forward. 

Compatibility 

MongoDB compatibility 

Note: The driver does not support older versions of MongoDB

Node.js DriverMongoDB 4.2MongoDB 4.0MongoDB 3.6MongoDB 3.4MongoDB 3.2MongoDB 3.0MongoDB 2.6
>= 3.X
>= 3.2.1
>= 3.1
>= 3.0

>=2.2.12


Language compatibility

Node.js
Driver
Node.js v0.8.XNode.js v0.10.XNode.js v0.12.XNode.js v4.X.XNode.js v6.X.XNode.js v8.X.XNode.js v10.x.xNode.js v12.x.x
>=3.X.X


2.2.X – 2.0.X

>=1.4.18




1.4.x





Few salient points 

When designing the schema for your database, a quick understanding of Embedded vs References is helpful. You can refer Coderwall for more information on this.  

Three of the other features that mongo provides: Indexing, Sharding and replicationcan make Mongo the right choice for your application. 

Indexing- supports ad hoc queries 

  • 64 indices per collection 
  • Single Field 
  • Compound (multiple Fields) 
  • Unique 

Sharding  - Scalability 

  • Partitions data onto different machines 
  • Scale application into smaller systems 
  • Autosharding supported by Mongo 
  • Challenging to set up

Replication

  • Reliability (Primary and n number of secondary server) 
  • Maximizes uptime 
  • Replica sets 
  • Automatic failover

Explore Mongo Shell 

  • Note:All the examples and snaps are taken in macOS. 
  • Invoke terminal and type ‘mongod’ which will display the listening port 27017

How to Create MongoDB Database in Node.js

  • Sinncewe are running locally, we need not secure and optimize it 
  • Invoke another terminal (command + T) and type ‘mongo’

How to Create MongoDB Database in Node.js

You should see that we are now connected to MongoDB://127.0.0.1:27017 

By default, we are connected to test database  

  • Type ‘db’ to check it in terminal and observe ‘test’ 

Let us use a different database say ‘MyNewMongoDB’ 

  • Type ‘use MyNewMongoDB’ 
  • Output: Switched to dbMyNewMongoDB 

To view all available dbs, type ‘show dbs’.

How to Create MongoDB Database in Node.js

Note: We will not see the new db ‘MyNewMongoDB’. Instead the db is created when the first document is created. 

Mongo stores data in databases which are separated into collections of documents. To Create a new collection, we need to insert a document and the collection will be created as a side effect. 

  • Type ‘db.cricketers.insert({“name”:”Sachin”}) 
  • Now check ‘show dbs’ to view our new db 
  • Type ‘show collections’ to check that our collection is created.

How to Create MongoDB Database in Node.js

As you can see, mongo doesn’t require any schema or setup work to start working with data. The commands we used are very similar to what we have in SQL but mongo shell uses a JavaScript interpreter. So, we can interact with database using JavaScript expressions making it easy to perform various tasks. 

  • Print(‘test’) will print test 
  • var arr = [“one”, “two”, “three”] 
  • type arrwhich will print the results. 

Let us take this option to explore further i.e. we will insert 1000 records to db using a for loop.

How to Create MongoDB Database in Node.js

for(i=0;i<1000;i++){ db.numbers.insert({"number":i}) } 

Though it says there was only one insert, it’s counting the number of operations and not individual documents. This is evident from the command ‘db.numbers.count()’ 

Now let’s try to find a single document from the database and understand the query better. 

  • Type ‘db.numbers.find({"number": 2})’ and this should display the one record. 
  • Let’s ask the mongo to explain it for us by adding the explain command.
  • db.numbers.find({“number”:”2”}).explain() 

How to Create MongoDB Database in Node.js

  • Explain did mentioned about the query planner but didn’t give much information about the execution. So, let’s pass execution status to get that information. 
  • db.numbers.find({“number”:”2”}).explain(“executionStats”)

How to Create MongoDB Database in Node.js

  • Now we can see that it ran through 999 records and took 0 milliseconds. May be if we increase the count to 1 million we can find higher time in executionTime. 
  • Since we don’t want to run through all the records, let’s create a simple index to see how the outcome changes. 
  • db.numbers.createIndex({number: 2}) 
  • Here it is similar to find but the number is a special variable and it is not a string. 

Now, let us try execution status again and see the result.

How to Create MongoDB Database in Node.js

As we can see, only one document is examined and imagine if we want to search in a collection of 10 million or more records. It makes a huge difference. 

Import data into the database: 

Though inserting data into mongo using shell or language driver is handy. Most of the time we have the data in some form which we need to import to our database. 

And Mongoimport command can import the data in json, csv or tsv formats and no custom code needed.In our case, we are using random data generated using

Sample view of the data downloaded:

How to Create MongoDB Database in Node.js

‘mongoimport –help’ will display the options available. 

  • Namespace options display the db and the collection to which the data has to be imported. 

  • Input options is next section in which we will use the file option. Json format is default one here. However, the file being imported is an array and not an object so we need to dash dash json array flag as well. 

Invoke the terminal and make sure we are in the file directory where the json file resides or downloaded.

How to Create MongoDB Database in Node.js

As we can see, we have imported 7 documents successfully.  

Now let us check if mongo has the data what we wanted 

  • Switch to mongo client and type ‘use MyNewMongoDB’ 
  • Type ‘show collections’ to view the collections now having persons. 
  • We can count records using commanddb.persons.count() or find using db.persons.find({“isActive”: true}). 

Mongo shell CRUD operations 

Now that we have the data in place, let’s explore the standard CRUD operations in database.If client is not running, start it by typing mongo in terminal and switch to newly created database ‘MyNewMongoDB’ 

  • [READ] In the available data,let’s find out the number of persons having eyecolor blue. 
    • GET: db.persons.find({“eyecolor”: “blue”}).count() 
    • This should result in count of 2 records. 
  • [CREATE] Now let’s go and add one more person with eyecolor blue. (INSERT) 
    • Insert is going to be little complex and might span across lines based on the data we insert.  
db.persons.insert({ "_id": "5eee4d58c952ec90ad43dfe8", "index": 7, "guid": "fbc2510e-678f-4843-b612-96b899ee5e9b", "isActive": true, "balance": "$3,996.47", "picture": "http://placehold.it/32x32", "age": 18, "eyeColor": "blue", "name": "SteuPoluard", "gender": "female", "company": "EXTRAWEAR"}) 

Note: In the above case, it is spanning multiple lines and Mongo is not going to execute/process until the last parenthesis isclosed and also _id is unique. 

  • Output should display one new record is inserted. 

WriteResult({ "nInserted" : 1 }) 
  • If we try to find the people with eye color blue, we should get 3 records.

How to Create MongoDB Database in Node.js

  • UPDATE] Now let’s go and update the inserted record with an email Id. 
  • Updates can happen to replace the entire document or a sub-set of the data. We wanted to add the email id without losing the entire object.For this we need to use the set functionality.
db.persons.update({"name":"SteuPoluard"}, 
... {$set: {"email":"Steu.Poluard@extrawear.com"}}) 

Output: 

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 
  • Now if we find the record to check if email is been added.

How to Create MongoDB Database in Node.js

  • Now if we want to update the tags then we need to use a different operator called $addToSet. 

db.persons.update({"name":"Sara Pollard"}, 
... { 
... $addToSet: {"tags":"newtag"} 
... })

How to Create MongoDB Database in Node.js

Note: There is a large set of update operators are available, refer to mongo site to explore this functionality in depth. 

  • [DELETE] Now lets finally delete the record added with name – ‘SteuPoluard’ 

db.persons.remove({"name":"SteuPoluard"}) 
  • To verify, let’s see if find command finds it. 

db.persons.find({"name":"SteuPoluard"}) 

No result. So, the record got successfully deleted. 

  • Say if we want to delete the collection itself. 

db.persons.drop() 
  • Check show collections to find the persons collection is no more.

Using MongoDBdriver for node.js 

Now let’s write some code in node.js to interact with the database. The drivers for all of the languages work similarly so once we have it working for node. Other language drivers should be pretty much same. 

The official MongoDB Node.js driver provides both callback-based and Promise-based interaction with MongoDB, allowing applications to take full advantage of the new features in ES6. The 2.x series of the driver is powered by a brand-new core driver and BSON library. To understand more about the changes made from drive 1.x to 2.x, refer to thisblog

First step is to make sure our Mongo server is up and running with db ‘MyNewMongoDB’ and the imported data collection i.e. person already in place. 

Note: In case if the collection is dropped, please follow the above steps to create and import the data

Steps:

  • Create an index.js file  
  • Setup the mongo client using MongoDB package. 
var MongoClient = require('MongoDB').MongoClient; 
  • Url for the database uses the MongoDB protocol and connects to the specified server. 

var url = 'MongoDB://localhost:27017/MyNewMongoDB'; 
  • Finally, we want to connect to the MongoClient and in the callback we log the connection is made successfully

varMongoClient = require('MongoDB').MongoClient; 
varurl = 'MongoDB://localhost:27017/MyNewMongoDB'; 
MongoClient.connect(url, function(err, db) { 
console.log("Connected successfully to server"); 
db.close(); 
}) 

Invoke a terminal and navigate to the index.js file folder. 

Type node index.js and observe that ‘Connected successfully to server’ 

Note: If you are facing any error, check if MongoDB server is running and npm install is performed. 

Now, let’s go ahead and try to access all the documents or specific document and print them in console. Since we have already made the connection. Let’s find the record in the callback of the connection. 

varMongoClient = require('MongoDB').MongoClient; 
// Server is running locally on the default port and db is name is 'MyNewMongoDB' 
varurl = 'MongoDB://localhost:27017/MyNewMongoDB'; 
varfindDocuments = function(db, callback) { 
// collection name is 'persons' which is imported 
varcollection = db.collection('persons'); 
// looking for a document with field 'name' and value 'Sara Pollard' 
collection.find({"name":"Sara Pollard"}).toArray(function(err, docs) { 
console.log(docs); 
callback(); 
    }) 
} 
MongoClient.connect(url, function(err, db) { 
console.log("Connected successfully to server"); 
// On obtaining the connection, find the record and close the db connection. 
findDocuments(db, function () { 
db.close(); 
    }) 
}) 

Type node index.js to check if the record is obtained successfully and is logged.

How to Create MongoDB Database in Node.js

As we can see, the same interfaces covered in the mongoShell work here as well for all CRUD operations. For sake of review, here is the list 

  • Create --> insert. 
  • Read --> find or findOne. 
  • Update --> update. 
  • Delete --> delete. 

Node.js based CRUD operations 

Let ussetup up a simple application using Node.js and MongoDB. We would understand how to setup the driver and perform simple CRUD operations. 

Follow the below steps to setup project 

  • mkdirlearnMongoDB 
  • cd learnMongoDB 
  • npminit [you would be prompted for inputs related to package.json] 
  • npm install MongoDB–save [--save is to update the package.json] 

Assuming that the mongo db server is still running. If not, start as mentioned earlier. 

Open the directory learnMongoDB in your favourite IDE. (I am using Visual Studio code). Add a file app.js with the below snippet of code. 

// import the MongoDB and get the client object. 
constMongoClient = require('MongoDB').MongoClient; 
constassert = require('assert'); 
// Connection URL - can be obtained in the MongoDB server 
consturl = 'MongoDB://localhost:27017'; 
// Database Name  
constdbName = 'myproject'; 
// Create a new MongoClient 
constclient = newMongoClient(url); 
// Use connect method to connect to the Server 
client.connect(function(err) { 
assert.equal(null, err); 
console.log("Connected successfully to server"); 
constdb = client.db(dbName); 
client.close(); 
}); 

Observe that we are not providing the db name in the URL. Instead we are getting the db instance on successfully connecting to the server. This way, we can get connected to different databases in the same client instances. 

Note: We are using assert module to check if connection is successful or not by validating the error object. Will be used for other CRUD operations as well. 

Run ‘node app.js’ and should observe the log mentioning connected successfully to server. 

Insertion: Now we have the db object, let’s get hold of the collection and insert some objects into it. 

Create a function ‘insertDocuments’ to perform insertion into the collection.Call this insertDocuments in the callback of successful connection. 

// insertDocuments take the db instance 
constinsertDocuments = function(db, callback) { 
// Get the documents collection 
constcollection = db.collection('documents'); 
// Insert some documents 
collection.insertMany([ 
      {a :1}, {a :2}, {a :3} 
    ], function(err, result) { 
assert.equal(err, null); // assertion to check if any error is there. 
assert.equal(3, result.result.n); 
assert.equal(3, result.ops.length); 
console.log("Inserted 3 documents into the collection"); 
callback(result); // return the inserted documents 
    }); 
} 
// Use connect method to connect to the Server 
client.connect(function(err) { 
assert.equal(null, err); 
console.log("Connected successfully to server"); 
constdb = client.db(dbName); 
//insert the documents and in the callback, close the client. 
insertDocuments(db, function(result) { 
console.log(result); 
client.close(); 
  }) 
}); 

In the callback of the insertDocuments, we get the result object which is as shown below: 

{ result: { ok: 1, n: 3 }, 

ops: 

[ { a: 1, _id: 5eeefd2a16f61641f58a9418 }, 
{ a: 2, _id: 5eeefd2a16f61641f58a9419 }, 
{ a: 3, _id: 5eeefd2a16f61641f58a941a } ], 
insertedCount: 3, 
insertedIds: 
{ '0': 5eeefd2a16f61641f58a9418, 
'1': 5eeefd2a16f61641f58a9419, 
'2': 5eeefd2a16f61641f58a941a } } 

As you can see, result object gives an overview of the action. Ops is the objects added to the collection. And other fields are self-explanatory. 

Note: You might have noticed that a new field ‘_id’ has been added which is generated by MongoDB for unique identification. If we are not happy with the unique id, we can as well supply like we did during importing of the data. 

Find: Let’s check if documents added can be retrieved using find. 

Collection object has a method called ‘find’ which take a parameter i.e. search query to identify the objects. If it is empty then all documents are returned.Invoke the findDouments in the callback of insertion for validating the records inserted. We can use a query filter to get specific item as well. 

// findDocuments from the db instance 
constfindDocuments = function(db, callback) { 
// Get the documents collection 
constcollection = db.collection('documents'); 
// Finds all documents. If required, parameterize the query filter to get specific items. 
collection.find({}).toArray(function(err, docs) { 
assert.equal(err, null); 
console.log("Found the following records"); 
console.log(docs) 
callback(docs); 
    }); 
  } 
// Use connect method to connect to the Server 
client.connect(function(err) { 
assert.equal(null, err); 
console.log("Connected successfully to server"); 
constdb = client.db(dbName); 
//insert the documents and in the callback, close the client. 
insertDocuments(db, function(result) { 
findDocuments(db, function() { 
client.close(); 
    })     
  }) 
}); 

For example, if we want to find a specific set of documents based on pre-defined query filter like ‘{‘a’:3}’ : 

// Find specific document with a query filter 
constfindDocuments = function(db, callback) { 
// Get the documents collection 
const collection = db.collection('documents'); 
// Find some documents 
collection.find({'a': 3}).toArray(function(err, docs) { 
assert.equal(err, null); 
console.log("Found the following record(s)"); 
    console.log(docs); 
callback(docs); 
  }); 
} 

Updation: Now go andupdate a specific document. There are various methods available for updation like update, updateMany, updateOne etc. Use updateOne method to update the first one which matches the query. 

Signature: updateOne(filter, update, options, callback) 

Let’s send the filter as {a : 2 } i.e. document whose field a is equal to 2, update as $set: {b:1} to avoid replacement of entire object i.e. adding a new field b to document with value set as 1. Ignore options which is an optional and have a callback to capture post actions. 

constupdateDocument = function(db, callback) { 
// Get the documents collection 
constcollection = db.collection('documents'); 
// Update document where a is 2, set b equal to 1 
collection.updateOne({ a :2 } 
      , { $set: { b :1 } }, function(err, result) { 
assert.equal(err, null); 
assert.equal(1, result.result.n); 
console.log("Updated the document with the field a equal to 2"); 
callback(result); 
    });   
  }   
// Use connect method to connect to the Server 
client.connect(function(err) { 
assert.equal(null, err); 
console.log("Connected successfully to server"); 
constdb = client.db(dbName); 
//insert the documents and in the callback, close the client. 
insertDocuments(db, function(result) { 
findDocuments(db, function() { 
updateDocument(db, function() { 
client.close(); 
        }) 
    })    
  }) 
}); 

Deletion: Let’s use deleteOne method to find and delete the first item with field a and value 3. 

constremoveDocument = function(db, callback) { 
// Get the documents collection 
constcollection = db.collection('documents'); 
// Delete document where a is 3 
collection.deleteOne({ a :3 }, function(err, result) { 
assert.equal(err, null); 
assert.equal(1, result.result.n); 
console.log("Removed the document with the field a equal to 3"); 
callback(result); 
    });     
  } 
// Use connect method to connect to the Server 
client.connect(function(err) { 
assert.equal(null, err); 
console.log("Connected successfully to server"); 
constdb = client.db(dbName); 
//insert the documents and in the callback, close the client. 
insertDocuments(db, function(result) { 
findDocuments(db, function() { 
updateDocument(db, function() { 
removeDocument(db, function(){ 
client.close(); 
            }) 
        }) 
    }) 
  }) 
}); 

Note: All the methods on the collection returns promise object if callback is not passed. So to avoid callback hell as we see above, we can rely on promise and program the code better. 

Node express app with MongoDB to store and serve content 

Now that we have fair idea of how to work with MongoDB using mongoshell and node.js driver. Let us build a simple app using node express app with MongoDB to store and serve content. 

Note: Since this topic is more about MongoDB rather than express, we will keep the express app a basic version. 

Let us go and comment out all the code in the app.js file from the previous example. We should be left with this: 

// import the MongoDB and get the client object. 
constMongoClient = require('MongoDB').MongoClient; 
const { equal } = require('assert'); 
// Connection URL - can be obtained in the MongoDB server 
consturl = 'MongoDB://localhost:27017'; 
// Database Name  
constdbName = 'myproject'; 

Invoke a terminal and navigate to the directory where the app.js file is located. 

Let us install express with the below command. 

  • npm install express –save 

Import the express and body-parser as shown below: 

constexpress = require('express'); 
constbodyParser = require('body-parser'); 
create an app instance and use bodyParser.json(). 
constapp = express(); 
app.use(bodyParser.json()); 
Let the express app be listening on port 3000 with a default route. 
app.get('/', (req, res) =>res.send('Express app with MongoDB!')); 
app.listen(3000, () =>console.log("App listening at http://localhost:3000")); 

Consolidated code: 

constexpress = require('express'); 
constbodyParser = require('body-parser'); 
// import the MongoDB and get the client object. 
constMongoClient = require('MongoDB').MongoClient; 
const { equal } = require('assert'); 
// Connection URL - can be obtained in the MongoDB server 
consturl = 'MongoDB://localhost:27017'; 
// Database Name  
constdbName = 'myproject'; 
constapp = express(); 
app.use(bodyParser.json()); 
app.get('/', (req, res) =>res.send('Express app with MongoDB!')); 
app.listen(3000, () =>console.log("App listening at http://localhost:3000")); 

In the terminal, run ‘node app.js’ and should see the console log that app is listening in port 3000. To check the default route is working correctly. Invoke the postman and perform get operation.

How to Create MongoDB Database in Node.js

Now let us create a new route to retrieve the document based on field a and parameterized value. 

app.get('/api/documents/:name', (req,res) => { 
}) 

:name is the parameter being passed. So let’s retrieve it from request parameters. And since we know it is numeric and not string. Let’s parse it to integer. 

constname = parseInt(req.params.name); 

Now lets connect to the MongoClient as earlier. This time we will not be using callback approach rather rely on the promise being returned. 

constclient = awaitMongoClient.connect(url, {useNewUrlParser:true});

Since returned object is a promise and in order for the promise to be resolved or rejected. We need to use await keyword before proceeding further. 

Note: Promise object has two properties i.e. state and result. Promise state property initially has ‘pending’ and post execution will be either ‘fulfilled’(resolve) or ‘rejected’(reject). Similarly, result will be ‘undefined’ initially and then changes to ‘value’[resolve(value)] or ‘error’[reject(error)]. 

Let us get the db ‘myproject’ and find the first document based on the query filter from collection using findOne method. 

constdb = client.db(dbName); 
constdocument = awaitdb.collection('documents').findOne({"a":name}); 

Once we get the document, lets return the status as 200 with the obtained document and close the client connection. 

res.status(200).json(document); 
client.close(); 

As we are using await keyword, we need to add async keyword to the callback. And also lets add a try-catch block to return an error status in case of connection failure as internal server error. 

app.get('/api/documents/:name',async (req,res) => { 
try {    
constname = parseInt(req.params.name); 
constclient = awaitMongoClient.connect(url, {useNewUrlParser:true}); 
constdb = client.db(dbName); 
constdocument = awaitdb.collection('documents').findOne({"a":name}); 
res.status(200).json(document); 
client.close();       
    } catch(error) { 
res.status(500).json({message:"Error connecting to db", error}); 
    } 
}) 

Now we are good to go and restart our express app. Press ctrl + c and run node app.js to see app is listening at. Make sure that MongoDB Server is up and running in the background. 

Switch to postman and perform a GET operation. This should return the first record in the collection as shown below. 

{"_id":"5eeefd2a16f61641f58a9419","a":2,"b":1} 

Same GET request can be performed for other documents by changing the name as 2

How to Create MongoDB Database in Node.js

Similar to get operations, we can configure the routes to perform other CRUD operations on MongoDB to store and serve the content.  

Conclusion 

In this guide, we have gone overMongoDB compatibility and language compatibility and explored the Mongo shell. We have seen how to import data into the database, how to use MongoDB driver and the Node.js based CRUD operations. We have also looked at how to build a simple app using node express app with MongoDB to store and serve content.

Armed with this knowledge, you are ready to take a deeper dive into MongoDB and NodeJS. Here’s wishing you the best! 

Real coding requires real exercises. Practice live coding with our programming  experts on live workshops now.

Sumanth

Sumanth Reddy

Author

Full stack,UI Architect having 14+ Years of experience in web, desktop and mobile application development with strong Javascript/.Net programming skills .Strong experience in microsoft tech stack and Certified in OCI associate. Go-to-guy on integration of applications, building a mobile app by zeroing on tech stack. Majorily experienced on engineering based IIOT products and Marekting Automation products deployed on premise and on-cloud. 

Join the Discussion

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

Suggested Blogs

Angular: Add service to module Code Example

What are services in an Angular app?Services is a general term broadly categorized as values, functions, or features that our application may need. Services are made to reuse codes designed for a purpose.Angular services differentiate an element from its service so that the services can be re-used. This increases the modularity of the Angular application. Service in an Angular App can be almost anything, it can be an element, a component, or it can be a module used for some specific purpose.All services in Angular App are classes with a definite purpose. It serves a purpose and serves it well.Some of the very well-known services include:Logging Service: Used for logging in, logging out.Data Fetching: Fetching Data and representing it in a formatted way.Data Service: Fetching and receiving Data.Message Bus: Used for communicating through a set of shared interfaces.Tax Calculator: Calculating Tax by synchronizing with the current Law system.EMI calculator: Easy Monthly Instalment Calculator, mainly used in calculations related to Loan. Application Configuration: Common configuration throughout the application support.ReusabilityReusability is very important when building large-scale applications. Classes built for a common purpose should not be required to be built again and again. This even causes misinterpretation of certain important classes. We need to implement separation of concerns to segregate different classes used for different purposes. This can be achieved by Angular services.In Angular 13 Framework, the services are those objects that get instantiated a maximum of one time during the entire lifetime of any Angular application or Angular module.All the Angular Services contain many methods that maintain data throughout the lifetime of an application. Thus, it has become a medium to share various responsibilities within one or multiple components.Services and Dependency InjectionServices provide us with injectable features. The Angular App provides us the decorator @Injectable for creating a service. Classes thereby created can be injected into any other module or component by calling it through service provider modules.The two-step process for creating a service in Angular application is:Use @Injectable decorator to create a class.Use Dependency Injection to inject the class or register the class with the service provider.In Angular 13 Framework, one of the ways of performing DI – Dependency Injection is by using Service injection. Dependencies are services or objects of a class that helps in performing its function. Dependency injection or DI are design patterns in which a class demands dependencies from external sources rather than constructing them.Building and providing servicesLet us build a service for keeping Records of Employees:Step 1: Install Node.js:Angular requires Node.js version 14.X.X or later. You can download it fromhttps://nodejs.org/en/download/The latest Version is : node-v16.13.1-x64Install node.js once downloaded:Once you have installed Node.js on your system, open node.js command prompt.To check your version, run node -v in a terminal/console window.Step 2: Use npm to Install Angular CLIUse the following command to install Angular CLInpm install -g @angular/cli Ornpm install -g @angular/cli@latestOrJust go to Angular CLI official website https://cli.angular.io/You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are same for Windows and Mac.To check Node and Angular CLI version, use ng --version command.Step 3: Create an app called ngApp4ServiceSyntax:ng new app_nameC:\>ng new ngApp4Service It asks forWould you like to add Angular routing? YesWhich stylesheet format would you like to use?> CSS….Step 4: Generate Service via CLI:Syntax for creating a service:ng generate service [options]ng g service [options]Let us generate the required service: here we are going to create “Employee” Service.Go to the app folder and install the required service: “Employee”:Step 5: Edit the service ts file:Service to store Employee Data: employee.service.tsFile name: employee.service.tsimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class EmployeeService { public _empList: Array = [];       constructor() {           this._empList = [{name:'Jay Choudhury', city:'Ghaziabad'}];       }        returnEmpData(): Array {           return this._empList;       }        addEmpData(item: any): void {           this._empList.push(item);       }   }Step 6: Import the employee service:Import the service in the app.module.ts:import { BrowserModule } from '@angular/platform-browser';   import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';   import { FormsModule, ReactiveFormsModule } from '@angular/forms';   import { AppComponent } from './app.component';   import { EmployeeService } from './employee.service';   @NgModule({     declarations: [       AppComponent     ],     imports: [       BrowserModule, FormsModule, ReactiveFormsModule     ],     providers: [EmployeeService],     bootstrap: [AppComponent],     schemas: [NO_ERRORS_SCHEMA]   })   export class AppModule { }Step 7: Use the service: Employee:Edit: app.component.tsimport { Component, OnInit } from '@angular/core';   import { EmployeeService } from './employee.service';   @Component({       selector: 'app-root',         templateUrl: './app.component.html',         styleUrls : ['./app.component.css']         })   export class AppComponent implements OnInit {         public model: any = {};         public source: Array;         constructor(public service: EmployeeService) {               this.source = this.service.returnEmpData();               }          ngOnInit(): void { }          public submit(): void {               if (this.validate()) {                   this.service.addEmpData(this.model);                   this.reset();               }           }         public reset(): void {          this.model = {};      }          public validate(): boolean {                  let status: boolean = true;                  if (typeof (this.model.name) === "undefined") {                         alert('Name is Blank');                         status = false;                         return status;                        }                  else if (typeof (this.model.city) === "undefined") {                         alert('City is Blank');                         status = false;                         return status;                        }                  return status;           }    }Edit app.component.html:         Employee Form             Employee Name                       City                                           Employee Details                                         Employee's Name                     City                                   {{item.name}}                         {{item.city}}                                     Step 8: Run to check the service:Go to the app folder:C:\>ng serveRun at localhost:http://localhost:4200/We get the Employee Form.We can add more details for the employee, and see the result.Importance of ServicesAngular App provides Angular Services as re-usable components of the application. It uses @Injectable Decorator for building a Service. A service can be called through multiple components as a common element and shared for various purposes. This helps in avoiding repetitive work and improves the speed of app development.
4975
Angular: Add service to module Code Example

What are services in an Angular app?Services is ... Read More

Create GraphQL API with example

Recently, GraphQL has made a lot of buzz among the developer community, and it has been receiving a lot of attention because of its dynamic nature along with its capability to fetch data, which is a lot less redundant. In this Code Tutorial, you will get to learn about what GraphQL really is, why has it created such hype amongst new-age developers, how is it different from the REST approach, and finally you will be building our own API with GraphQL along with Code Tutorials. Let’s get started!What is GraphQL? A quick primerBefore understanding what GraphQL is, let’s first understand what Query Languages are. Query Languages are computer languages that request the data from a database (called queries) to a client-side application through a server. A well-known example is Structured Query Language or SQL.Coming to GraphQL, by definition - “GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data” (source: Wikipedia). Simply put, GraphQL is a new age Query Language developed by Facebook in 2012 that helps Application Programming Interfaces (APIs) fetch only that data which is requested by the client, and nothing else. This enormously reduces the redundant data at the API endpoint and making the requests blazing fast and developer friendly.Initially, GraphQL was an internal project of Facebook and it was created for fetching specific data and reducing network usage. In 2015, it was released publicly at the React.js conference and reference implementations and specifications of GraphQL in JavaScript were open-sourced. Later most of the programming languages adopted that. New languages like Python, Node.js, Java, C#, PHP, GO, and many more, support GraphQL.But wasn’t the same thing already being done by RESTful APIs? The answer is yes, but GraphQL is different than REST in a lot of ways.GraphQL is Client-Driven, whereas REST is Server-Driven.Queries are organized in terms of Schema and strict typecasting in GraphQL, whereas REST has Endpoints for that task.GraphQL calls Specific data with a single call. REST calls Fixed data with multiple calls.Instead of the GET, POST, PUT, DELETE operations in REST, GraphQL has Query, Mutation, and Subscription for data manipulation.Some of the other advantages of using GraphQL are:GraphQL is faster than other communication APIs.GraphQL can retreat multiple resources and results with a single request.It is easy to use complex systems and microservices with GraphQL as it unifies and hides their complexity.It offers multiple libraries and powerful tools for various projects such as GraphiQL, GraphQL Explorer, Apollo.No under and over data fetching. It fetches the amount of data that is required.The core building block of GraphQL is its schema which is used as a middle way between server and client while defining the accessibility of the data.  A GraphQL schema is written in Schema Definition Language (SDL) and refers to the exact mutations and queries that a client can execute against your data graph. It can be built with any programming language. Simply, the schema defines the type of data that can be fetched, the relationships between these types of data, and what type of queries are allowed. The most basic components of a GraphQL schema are object types. They represent a kind of object you can fetch from your service along with the fields it has. Further, schema helps the client validate their query and eliminate unavailable data or the wrong structure stage.The other two fundamental parts of GraphQL are Query and Resolver. The request to fetch a particular data is called a query and a resolver is used to tell the server from where and how to fetch the data corresponding to the given field. You can execute the GraphQL queries either by Command line or by using a GraphQL server.GraphQL works in three parts – a query to read data, a mutation to write data, and a subscription to receive real-time data over time.Now that you know the ‘What’ and ‘Where’of GraphQL, let’s dive straight into our favorite part, the development phase.Let’s Play with GraphQLTo get started with GraphQL, you need a server that serves your API and a client that connects to your service endpoints. In this section, you will learn about a step-by-step procedure of building an API using GraphQL and Express on top of Node.js. In the next section, you will be implementing these prerequisites into code and start our development for the API.Prerequisites:Understanding of GraphQLNode Package Manager (or NPM) with version 10+Knowledge of basic querying and server-side programming.We will be needing a database to store the user data and everything else that a client-side application can request for. For this, you will be using LowDB, which is a simple file based JSON database for small projects in the localhost. Then you will be needing middleware to connect our database system to the requesting frontend application. For this, you will be using the Express middleware with the GraphQL implementation of Express - the Graphql-express library. Finally, you will be making a client-side application using react which can request all the data from the local database and can perform operations on the database like read, write, and delete.So, our roadmap is simple and straightforward. Create a Database Schema > Use a middleware server to query the database > Create a frontend application to use the data. If this is too much at once for you, do not worry as this is article is being written keeping in mind that the reader is a first-timer for GraphQL and basic querying as usual. Now, let’s dive into the code.Setting up Express GraphQLLet’s begin with the basic project structure of a Node.js application. Begin a new project in a new folder.$ mkdir graphql-example $ cd graphql-exampleUse NPM to intiialize a project$ npm init -yInstall the required dependencies for Express, MongoDB (Mongoose), and some additional dependencies required for the function of Express.$ npm install express mongoose body-parser cors --saveApollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks, so next, you are going to download and save that.$ npm install apollo-server-express --saveThis should’ve created a package.json and a package-lock.json file within your folder. These files contain information regarding our environment, the dependencies, and the specific versions to run those dependencies.This means our environment is ready and you can now start developing the integrated server and API. We are going to write the Schema inside the index.js file. In the index.js file, start off by writing this code.const express = require('express'); const mongoose = require('mongoose'); const schema = require('./schema'); const bodyParser = require('body-parser'); const cors = require('cors'); const { ApolloServer } = require('apollo-server-express'); const url = "mongodb://localhost:27017/moviesdb"; const connect = mongoose.connect(url, { useNewUrlParser: true }); connect.then((db) => {       console.log('Connected correctly to server!'); }, (err) => {       console.log(err); }); const server = new ApolloServer({       typeDefs: schema.typeDefs,       resolvers: schema.resolvers }); const app = express(); app.use(bodyParser.json()); app.use('*', cors()); server.applyMiddleware({ app }); app.listen({ port: 4000 }, () =>   console.log(`Server ready at  http://localhost:4000${server.graphqlPath}`));In lines number 1 to 6, you’re implementing the necessary modules. Note that here you have imported the ./schema, but you haven’t created that yet. We will be doing this in the next step.In lines number 9 to 14, you are connecting the project to the MongoDB database and logging any error you face to the console.In lines number 16 to 19, you’re creating a new Apollo Server with typeDefs and Resolver. We’ll be defining those in the ./schema later in this tutorial.In lines 21 to 26, you’re firing up the Express Server at port 4000, when you will actually be able to interact with what you’re building.GraphQL has two main principles to work: types and resolvers. We defined them in Apollo Server. We’ll import them from the file you’ll create later.Next, let’s create the file models/movie.js that’ll contain the movie-Mongoose model.const mongoose = require('mongoose'); const Schema = mongoose.Schema; const movieSchema = new Schema({     name: {        type: String,        required: true     },     rating: {        type: Number,        required: true     },     producer: {        type: String,        required: true    } }, {     timestamps: true }); var Movies = mongoose.model('Movie', movieSchema); module.exports = {Movies, movieSchema};We’re going to build a simple movie app, where you can show, add, edit, and delete movies. That way you’ll get through the basics of GraphQL, which is the main goal of this tutorial.In lines 4 to 19, you’re basically determining the schema of the database that is going to hold the data of movies. Every movie is going to have a Name and a Producer of type String and a Rating of type Number.Designing the SchemaLet’s move on to the schema.js file where you’re going to build our GraphQL API.Create a new file in the root of the folder by the name of schema.js and add the following code.const { gql } = require('apollo-server-express');   const Movie = require('./models/movie').Movies;   const typeDefs = gql `    type Movie {      id: ID!      name: String!      producer: String!      rating: Float!  }  type Query {    getMovies: [Movie]    getMovie(id: ID!): Movie  }  type Mutation {      addMovie(name: String!, producer: String!, rating: Float!): Movie      updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie      deleteMovie(id: ID!): Movie    } `In this, you’re building the schema. We defined the Movie type which will have an ID, the name of the movie and the producer, and a rating of type Float. The “!” after the types shows that these fields are necessary.Unlike the REST approach of getting different tasks done at different endpoint URLs, GraphQL can create operations in a single endpoint. That is what you have done in line 11 onwards. The type Query determines the GET operations, and type Mutation determines the modification operations like POST, DELETE, etc. In getMovies, you’re returning a list of all available movies in our database, and in getMovie, you’re getting the specific movie by the ID of that movie.Now you’re going to link these with the Mongoose Database queries that are going to perform the actions in the database. And this is done by Resolvers. Resolvers are a collection of functions that connect schema fields and types to various backends. It can read, write, and delete data from and to anywhere in the database, be it SQL, NoSQL, or Graph-based database. In simple terms, they act as a GraphQL query handler. Here’s how you’re going to implement Resolvers in our code:const resolvers = {   Query: {     getMovies: (parent, args) => {       return Movie.find({});     },     getMovie: (parent, args) => {       return Movie.findById(args.id);     }   },   Mutation: {     addMovie: (parent, args) => {       let movie = new Movie({         name: args.name,         producer: args.producer,         rating: args.rating,       });       return movie.save();     },     updateMovie: (parent, args) => {       if (!args.id) return;         return Movie.findOneAndUpdate(          {            _id: args.id          },          {            $set: {              name: args.name,              producer: args.producer,              rating: args.rating,            }          }, {new: true}, (err, Movie) => {            if (err) {              console.log('Something went wrong when updating the movie');            } else {              continue;            }          }       );     }   } } module.exports = {typeDefs,resolvers};This is the basic logic of MongoDB and CRUD applications, which doesn’t come under the scope of this article, since it is majorly focused on GraphQL. However, the logic is simple and straightforward for anyone to understand, so skim through it once.With this, you’re done with a basic Movie API that can perform all the CRUD operations on a database of movies. To test this out, you’re going to fire up our node server and open the browser in http://localhost:4000/graphql which will open the GraphQL Playground.$ node index.js Server ready at http://localhost:4000/graphqlOnce the Playground UI opens, you’re first going to create a Movie Record for the database since it would initially be empty.mutation { addMovie(name: “GraphQL Movie”, producer: “Facebook”, rating:  4.5) { id, name, rating, producer } }OUTPUT:{ “data” : { “addMovie”: { “id”: “5j2j1lnk1LNS231MLK3”, “name”: “GraphQL Movie”, “producer”: “Facebook”, “rating”: 4.5 } } }And now let’s list out all the movies in the database with only their “name” and “rating”.query { getMovies: { name, rating } }OUTPUT:{ “Data”: { “getMovies”: [ { “name”: “GraphQL Movie”, “rating”: 4.5 } ] } }So, you have successfully created a Movie API where you can perform all the CRUD operations on a single endpoint, and also ask for just the data that you want.  This results in a blazing fast API response and a developer-friendly return object that makes development fast and easy.Using GraphQL with ReactUsing GraphQL with react is super easy and can make full-stack development look like a piece of cake. We’re going to build a react app that uses the Movie API you just built to render the results on a frontend client app.Start off by installing the required dependencies.$ npm install create-react-app graphql @apollo/clientCreate a new React appnpx create-react-app movies-appLet’s start off by initializing an ApolloClient instance. In index.js let's first import the symbols you need from @apollo/client, Next, you'll initialize ApolloClient, passing its constructor a configuration object with URI and cache fields:import {   ApolloClient,   InMemoryCache,   ApolloProvider,   useQuery,   gql } from "@apollo/client"; const client = new ApolloClient({   uri: 'https://48p1r2roz4.sse.codesandbox.io',   cache: new InMemoryCache() });The URI specifies the GraphQL Server URL.That’s it! Our client app is ready to fetch data from the GraphQL server. In index.js, let’s wrap our React app with the ApolloProvider Component. Put up the ApolloProvider somewhere high in the app, above any component that might need to access GraphQL data.function App() {   return (           My first GraphQL app       ); } render(         ,   document.getElementById('root'), );With this being done, our client app is now ready to request data from the server and perform queries on the frontend. We can do this using the useQuery React Hook that shares the GraphQL data with the UI.In the index.js, let’s first define the query you want to execute.const MOVIES = gql`   query getMovies {      name,      producer   } `;Next, let's define a component called GetMovies that executes our getMovies query with the useQuery hook:function GetMovies() {   const { loading, error, data } = useQuery(MOVIES);   if (loading) return Loading...;   if (error) return Error :(;   return data.map(({ name, producer }) => (                   {name}: Produced by {producer}             )); }Whenever this component renders, the useQuery hook automatically executes our query and binds the results to the data property on successful completion of the query.Finally, you'll add GetMovies to our existing component tree:function App() {   return (           My first Apollo app             ); }When your app reloads, you should briefly see a loading indicator, followed by a list of Movies present in the MongoDB database.Congratulations. You just made a React app that uses GraphQL to render data from the server. Give yourself a pat on the back for this one.Dev-friendly Query Languages are the FutureSo, wrapping it all up in a few more lines. In this tutorial, you learned what GraphQL is - a new age Query Language that is data specific and client-oriented, how is it different (and better) than REST architecture - it is developer friendly, blazing-fast, and easy to learn or understand. We also made a mock API of Movies using GraphQL and MongoDB and performed the CRUD operations using just one single endpoint URL - another benefit over the RESTful architecture. And finally, you went on to create a React application that uses these benefits of GraphQL and combines them with the benefits of React to give a hyper-fast, easy, and full-stack app that renders Movies on request.We hope you learned something new from this article. Once you’ve started this journey of GraphQL, it is a fun ride ahead since it is a relatively new tech and not many people out there are having this skill under their hood. So, make use of this opportunity and outshine the rest.Keep Learning.
4805
Create GraphQL API with example

Recently, GraphQL has made a lot of buzz among the... Read More

How to use Timers in Node.js

You can use Node.js's utilities to schedule the execution of your code. The timer module, unlike most Node.js modules, is not imported. To comply with the JavaScript browser API, the methods are globally accessible.The Node.js Timers module contains several functions that allow you to execute a block of code or a function after a specified amount of time. You don't need to use require() to import the Timers module because it's global.In this post, I'll explain and demonstrate what timers are, how to use them, how the syntax looks, and how you can use them in your applications. For example, if you want to retrieve data from a REST API at a specific interval, you can easily do so with timers. So, even if you are unfamiliar with JavaScript or timers, this post will help you understand these concepts.The Event Loop - A Quick PrimerNode.js is a single-threaded, event-driven platform that can run non-blocking, asynchronous code. These Node.js features make it memory efficient. Even though JavaScript is single-threaded, the event loop enables Node.js to perform non-blocking I/O operations. It is accomplished by delegating tasks to the operating system whenever and wherever possible.Because most operating systems are multi-threaded, they can handle multiple operations that are running in the background. When one of these operations is finished, the kernel notifies Node.js, and the callback associated with that operation is added to the event queue, where it will eventually be executed.Features of Event Loop:An event loop is an infinite loop that waits for tasks, executes them, and then sleeps until more tasks are received.When the call stack is empty, i.e., there are no ongoing tasks, the event loop executes tasks from the event queue.We can use callbacks and promises in the event loop.The event loop executes the tasks in reverse order, beginning with the oldest.Example:console.log("One"); setTimeout(function(){ console.log("Two"); }, 1000); console.log("Three");Output:OneThreeTwoThe first console log statement is pushed to the call stack in the above example, and "One" is logged on the console before the task is popped from the stack. Following that, the setTimeout is added to the queue, the task is sent to the operating system, and the task's timer is set. After that, this task is removed from the stack. The third console log statement is then pushed to the call stack, "Three" is logged on the console, and the task is removed from the stack.Timers in JavaScriptA timer is used in JavaScript to execute a task or function at a specific time. The timer is essentially used to delay the execution of the program or to execute the JavaScript code at regular intervals. You can delay the execution of the code by using a timer. As a result, when an event occurs or a page loads, the code does not complete its execution at the same time.Advertisement banners on websites, which change every 2-3 seconds, are the best example of a timer. These advertising banners are rotated at regular intervals on websites such as Flipkart. To change them, you set a time interval.JavaScript provides two timer functions, setInterval() and setTimeout(), which help to delay code execution and allow one or more operations to be performed repeatedly.setTimeout():The setTimeout() function allows users to postpone the execution of code. The setTimeout() method accepts two parameters, one of which is a user-defined function, and the other is a time parameter to delay execution. The time parameter, which is optional to pass, stores the time in milliseconds (1 second = 1000 milliseconds).setInterval():The setInterval method is similar to the setTimeout() function in some ways. It repeats the specified function after a time interval. Alternatively, you can say that a function is executed repeatedly after a certain amount of time specified by the user in this function.Timers in Node.js - setTimeout()setTimeout() can be used to execute code after a specified number of milliseconds. This function is equivalent to window. setTimeout() from the browser JavaScript API, but no code string can be passed to be executed.setTimeout() takes a function to execute as the first argument and a millisecond delay defined as a number as the second. Additional arguments may be provided, and these will be passed to the function. As an example, consider the following:Using setTimeout()The timeout interval is not guaranteed to execute after that exact number of milliseconds. This is because any other code that blocks or holds onto the event loop will delay the execution of the timeout. The only guarantee is that the timeout will not be executed sooner than the timeout interval specified.setTimeout(function A() { return console.log('Hello World!'); }, 2000); console.log('Executed before A');clearTimeout():The clearTimeout() method deactivates a timer that was previously set with the setTimeout() method.The ID value returned by setTimeout() is passed to the clearTimeout() method as a parameter.Syntax:clearTimeout(id_of_settimeout)Example: function welcome () { console.log("Welcome to Knowledgehut!"); } var id1 = setTimeout(welcome,1000); var id2 = setInterval(welcome,1000); clearTimeout(id1);Timers in Node.js - setImmediate()To execute code at the end of the loop cycle, use the setImmediate() method. In layman's terms, this method divides tasks that take longer to complete, in order to run a callback function that is triggered by other operations such as events.Syntax:let immediateId = setImmediate(callbackFunction, [param1, param2, ...]); let immediateId = setImmediate(callbackFunction);The function to be executed will be the first argument to setImmediate(). When the function is executed, any additional arguments will be passed to it.Now consider the difference between setImmediate() and process. nextTick(), as well as when to use which.While processing, setImmediate() is executed in the Check handlers phase. process.nextTick() is called at the start of the event loop and at the end of each phase.process.nextTick() has higher priority than setImmediate():setImmediate(() => console.log('I run immediately')) process.nextTick(() => console.log('But I run before that'))Output:Using setImmediate()Multiple setImmediate functions are called in the following example. When you do this, the callback functions are queued for execution in the order in which they are created. After each event loop iteration, the entire callback queue is processed. If an immediate timer is queued from within an executing callback, it will not be triggered until the next iteration of the event loop.Example:setImmediate(function A() { setImmediate(function B() { console.log(1); setImmediate(function D() {   console.log(2); }); }); setImmediate(function C() { console.log(3); setImmediate(function E() {   console.log(4); }); }); }); console.log('Started');clearImmediate():The clearImmediate function is used to remove the function call that was scheduled by the setImmediate function. Both of these functions can be found in Node.js's Timers module.Example:console.log("Before the setImmediate call") let timerID = setImmediate(() => {console.log("Hello, World")}); console.log("After the setImmediate call") clearImmediate(timerID);Timers in Node.js - setInterval()This method, unlike setTimeout(), is used to execute code multiple times. For example, the company may send out weekly newsletters to its Edge as a Service customer. This is where the setInterval() method comes into play. It is an infinite loop that will continue to execute as long as it is not terminated (or halted).As the second argument, setInterval() accepts a function argument that will run an infinite number of times with a given millisecond delay. In the same way that setTimeout() accepts additional arguments beyond the delay, these will be passed on to the function call. The delay, like setTimeout(), cannot be guaranteed due to operations that may stay in the event loop and should thus be treated as an approximation.Syntax:let intervalId = setInterval(callbackFunction, [delay, argument1, argument2, ...]); //option 1 let intervalId = setInterval(callbackFunction[, delayDuration]); // option 2 let intervalId = setInterval(code, [delayDuration]); //option 3Using setInterval()Example:setInterval(function A() { return console.log('Hello World!'); }, 1000); // Executed right away console.log('Executed before A');setInterval(), like setTimeout() returns a Timeout object that can be used to reference and modify the interval that was set.In the above example, function A() will execute after every 1000 milliseconds.clearInterval():Example:var si = setInterval(function A() { return console.log("Hello World!"); }, 1000); setTimeout(function() { clearInterval(si); }, 4000);Using Timer.unref()The timer module is used to schedule functions that will be called later. Because it is a global API, there is no need to import (require("timers")) to use it.The Timeout Class contains an object (setTimeout()/setInterval()) that is created internally to schedule actions, and (clearTimeout()/clearInterval()) that can be passed to cancel those scheduled actions. When a timeout is set, the Node.js event loop will continue to run until clearTimeout() is called. The setTimeout() method returns timeout objects that can be used to control this default behaviour, and it exports both the timeout.ref() and timeout.unref() functions.timeout.ref():When the Timeout is active and (timeout.ref()) is called, it requests that the Node.js event loop not exit for an extended period of time. In any case, calling this Method multiple times has no effect.Syntax:timeout.ref()timeout.unref():When the Timeout is enabled, the Node.js event loop is not required to remain active. If any other activity keeps the event loop running, the Timeout object's callback is invoked after the process exits. In any case, calling this Method multiple times has no effect.Syntax:timeout.unref()Example:var Timeout = setTimeout(function alfa() { console.log("0.> Setting Timeout", 12); }); console.log("1 =>", Timeout.ref()); Timeout.unref() Timeout.ref() console.log("2 =>", Timeout.unref()); clearTimeout(Timeout); console.log("3 => Printing after clearing Timeout"); Output:Scheduling Made SimplerIn this tutorial, you learned how to schedule tasks with the Node.js timer module. You've seen how to set timeouts, interval timers for recurring tasks, and how to use set immediate to bypass long operations. You've also seen how to stop these operations using the clear() method for each method.As with learning anything new, practising what you learn will make a big difference to how easily you can perform these tasks. Share your thoughts and questions in the comments as you try out what you’ve learnt.
2239
How to use Timers in Node.js

You can use Node.js's utilities to schedule the ex... Read More