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

How to Become a Successful Full Stack Web Developer?

Full stack developer roles are among the hottest careers in the tech space now. These talented folks can develop a whole product from scratch. A full stack developer is a combination of Front-end developer and Backend developer. These two in themselves are full time jobs and most people make careers out of one of them. So, we will start with Front-end roadmap and then go to Back-end roadmap. A person interested in becoming a Full-stack developer needs to have proficiency in both the front end and back-end tools, just like I started as a Front-end developer and later on become a Full stack developer by mastering JavaScript backend technologies and databases.The demand for Full Stack Web DeveloperThe demand for Full stack developers is the highest in early-stage startups, where they want to create a Minimum Viable Product at the earliest to showcase to the investors. It is also a nice skill to have in addition to frontend technologies or backend technologies alone, since an employer prefers people with both skills.There are a lot of technologies to learn to be a Full-Stack developer. We will discuss about them in the coming sections.   List of technologies to master to become a Full-Stack developer A full-stack developer is actually a combination of Frontend developer and Backend developer. We need to master both, and both have different Roadmaps. Let’s start with the basics. The frontend is the web-site which we see and it is primarily made with HTML and CSS.  JavaScript was also used earlier but nowadays, it is created with JavaScript frameworks like ReactJS, Angular or Vue. All these frameworks require one to learn the basics of HTML, CSS, & JavaScript. So, we need to learn the basics followed by at least one framework.In the backend we have a lot of technologies and databases also. So, we need to choose one backend framework from Java (Spring Framework), JavaScript (NodeJS) etc and then also learn databases. Databases are divided into two categories, which is NoSQL(MongoDB) and SQL(PostgreSQL, MySQL, Oracle) databases. So, you need to choose one of the databases.We are also required to know about DevOps, which is a practice of harmonizing development and operations whereby the entire pipeline from development, testing, deployment, continuous integration and feedback is automated. The knowledge of either AWS or Azure based cloud ecosystem is required, and also CI/CD like Jenkins and containerizing & orchestrating applications using Docker and Kubernetes.1. Frontend RoadmapLearn the BasicsPlease refer to the attached figure for Front-end roadmap, as we will be referring to this throughout this article. We have to start our journey by learning HTML, CSS and JavaScript which is the base for a web-app or website. HTML has changed a bit over the years, with the introduction of HTML 5 and semantics tags, so make sure to update yourself. JavaScript which was released in 1995, didn’t change much during the next 20 years. But once more and more developers started using it, the ECMA committee decided to add some very nice features and enhance the language, and renamed it ES6 in 2015. After that they regularly added new features to the language and have just released ES2020 in June 2020, which has many additional features. So, learn the basic JavaScript first and then upgrade to ES6 and newer versions. CSS is what makes a website or web-app beautiful, and is often considered the hardest part by a developer. Earlier, CSS was very confusing and had a steep learning curve, because of the use of floats to create a layout. Developers usually used to work with CSS frameworks like bootstrap to design a site. But things have changed a lot with the invention of CSS Grid and Flexbox. Some of the best resources to learn the basics are - html.specdeveloper.mozilla.HTMLStyle CSSdeveloper.mozilla.CSSdeveloper.mozilla.JavaScriptGetting Deeper Now, just learning JavaScript and some basic CSS will not make you a good Front-end developer as you have to take a deep dive into JavaScript. We will discuss CSS later, after learning the essentials of JavaScript.JavaScript EssentialsThere are many things associated with JavaScript which we need to learn before moving forward.The Terminal The first thing to learn is to work in a terminal, and master some of the basic commands. If you are on a Mac, it’s already based on Linux and runs most Linux commands. If you are working on Windows then you must install git bash, which will give you a Linux environment to work with. In JavaScript frameworks, we need to run a lot of commands from the terminal, like if we want to install a third-party dependency by npm.  The basics of Linux can be learnt from their official site.1. Linux FoundationVersion ControlNext, learning version control is very important because we should always keep our code in some remote repository like Github. The industry works on Git, which is version control software. It is completely command-based and is used heavily everywhere. Learn the basic commands which will be useful even for an individual developer. Later on, when working with teams, more advanced knowledge of the git command is required.Through the git commands, we store our code in repositories. The most popular ones are Github and Bit Bucket, so we need to learn how to store and link them.The basics of git can be learnt from this awesome tutorial.1. Git TutorialTask Runners   Task runners are applications which are used to automate tasks required in projects. These tasks include minification of JavaScript and CSS files, CSS preprocessing like from SASS to CSS, image optimization and Unit testing. The three popular task runners are npm scripts, gulp and grunt. The npm script is nothing but the package.json file which comes with React projects or is created in a Node.js project using npm init. Gulp and Grunt are much bigger applications and also have a plugin ecosystem that is suited for large JavaScript projects. The basics for these two technologies can be learnt from here. 1. Gulp2. GruntModule Loader and Bundler  Both module loaders and bundlers are required for large JavaScript applications. Knowledge of both is required, if the project you are working is a big Vanilla JavaScript project. When a large JavaScript application consists of hundreds of files, the module loader takes care of the dependency and makes sure all the modules are loaded when the application is executed. Examples are RequireJS and SystemJS.Module bundlers also do the same thing, building it at the time of application build rather than at the runtime. Popular examples are Webpack and Rollup. 1. RequireJS2. Github3. Webpack4. RollupJSTesting  Testing nowadays is very important in any type of project. There are two types of testing; one is known as Unit testing and other as end-to-end testing. For unit testing we write test cases and the most popular tool nowadays is Jest. End-to-end testing is automated testing, which emulates the whole app. Suppose, an app has a login screen and then it shows posts. The testing tool will run the web-app to check whether all the functionalities are done correctly. The two most popular options today are Puppeteer and Cypress. The tutorials to refer for these topics are - 1. Jest2. Puppeteer3. CypressLibraries and FrameworkThey are the most important part of the JavaScript ecosystem nowadays. It all started with the release of AngularJS in 2010. Before that period most enterprise apps were made in Java and were desktop apps. But AngularJS changed everything, because it made it easy to manage big projects with JavaScript and helped to create complex web-apps.1. React   It is the most popular JavaScript library today and is used by both enterprises and startups that have a huge ecosystem. It is not a complete framework like Angular and we have to install third party dependencies for most things. But if you want to learn a framework that will get you a job, then that framework would be ReactJS, and its demand is not going away for the next 5 years. The component approach and its easy learning curve have made React more popular than other frameworks. A good starting tutorial for React is1. ReactJSState Management   In React state management can sometimes become complex, when we need to share data between components. We generally take help of external packages in it with the most popular being Redux. But we also have other state management libraries like XState and Recoil. Server-side rendering   With performance becoming important nowadays, Server-Side Rendering speeds up the React projects even faster. In SSR projects, the React code is rendered on the server and the client browser directly receives the HTML, CSS, JS bundle. The only framework to do it is NextJS. Static Site Generators   Lot of sites don’t need to be updated frequently and it is the place where the only Static Site Generator for ReactJS, which is GatsbyJS shines. With the help of GatsbyJS we can create extremely fast static sites and it gets into Wordpress domain a lot with it. GatsbyJS also has a huge ecosystem of plugins, which enhances its functionalities. React Testing   Unit testing is a very important part of ReactJS projects, especially the ones which are very large. Unit testing ensures that we have lower bugs in Production build. The two popular libraries are – Enzyme and Jest. 2. Angular    It is a complete framework and unlike React requires very few external dependencies. Everything is built within Angular and we don’t have to go outside for more features. Since it was among the earliest frameworks, older projects are in Angular and it is still widely used in enterprises. A good tutorial to learn Angular is below. Angular3. Vue    Vue is another very popular JavaScript library, which has the best features of both ReactJS and Angular and has become very popular in recent years. It is widely used in both enterprise and startups. A good tutorial to start with Vue is below. Vue4. NuxtJS   It is used for Server-Side Rendering in Vue projects and is similar to the NextJS framework used in ReactJS for SSR.  5. Svelte    It is the newest of all frameworks/libraries and has become quite popular, but still not used much in enterprises and startups. It is different from React, Vue and Angular and converts the app at build time rather than at run time as in the other three. Good tutorials to start with Svelte are below. SvelteSvelte handbookCSS Deep DiveA lot has changed in CSS after it included CSS Grid and Flexbox; it has become much easier for developers to work with. CSS Essentials   It is now mandatory for frontend developers to learn CSS Grid and Flexbox, because through it we can develop beautiful layouts with ease. More companies are moving away from CSS Frameworks and have started working with CSS Grid and Flexbox, which are now supported by all browsers. Good tutorials to learn Flexbox and CSS Grid are below. CSS FlexboxCSS GridCSSPreprocessors  CSS preprocessors are used to add special functionalities in CSS, which it lacks. An example is Sass, which adds special features like variables and nested rules in CSS and is widely used in the industry for larger projects. The other popular one is PostCSS, in which we can use custom plugin and tools in CSS. CSS Frameworks  Frameworks were very popular from the early days of CSS, when it was very complicated because of floats. Bootstrap  This is the most popular and oldest CSS framework; easy to learn and also has a wide variety of elements, templates and interfaces. Bulma   It is another CSS framework, which is very popular and much easier to use than bootstrap. Tailwind CSS   This is a fairly new CSS framework and is quite popular nowadays. It follows a different approach than the other frameworks and contains easier classes. Styled Components (React)   This is a CSS in JS library and is for React only. It is used to create components out of every style and is very popular in the React world.  CI/CDThe Continuous Integration/ Continuous deployment is mainly used by DevOps. But a frontend engineer should know its basics. It is used to build, test and deploy applications automatically.Github Actions    It is a freely available CI/CD pipeline, which directly integrates to your github based project and can be used in a variety of languages. Deployment It is again a task which mainly falls into the domain of Backend engineers and DevOps, but a frontend engineer should know some basic and simple tools. Static Deployment   These products are mainly used to deploy static sites, which consists of HTML, CSS and JavaScript only. Two very popular services are Amazon S3 and Surge.sh Node Application Deployment   The projects containing node code cannot be deployed using static deployment. Even if the project is a simple ReactJS project, it also uses node for processing. These applications require services which run the Node code and deploy it. The three most popular services are Vercel, Firebase and Netlify. 2. Backend Roadmap (Including Storage, Services & Deployment)Understanding the BackendBackend is the part of the website that provides the functionality, allowing people to browse their favorite site, purchase a product and log into their account, for instance. All data related to a user or a product or anything else are generally stored in databases or CMS (Content Management System) and when a user visits any website, they are retrieved from there and shown. One of the responsibilities of a backend engineer involves writing APIs, which actually interact with the database and get the data. They are also involved in writing schemas of database and creating the structure of databases. Backend EssentialsFor a backend engineer, working in a Linux environment is an essential skill. A lot of the configurations are done on the terminal. So, he or she should be very good with Linux commands.Also, they should know both commands and the use of any git powered platforms like Github or bitbucket.Languages and FrameworksAll of the popular languages have some framework, which has been used for backend development. These frameworks are generally used to create API endpoints, which are used to fetch or store data in the database. For example, when we scroll articles on Facebook, these articles are fetched from a database and we use the GET method to fetch them. Similarly, when we write an article and hit submit, it uses POST method.Now, different frameworks implement this GET, POST and other APIs also referred to as RESTful APIs in their own way.Java   Java is by far the oldest and the most used language for backend development. It is also used for a variety of other tasks like Android development, but it shines in the backend because of its multithreading abilities. So, enterprise grade web-apps and web-apps with a lot of traffic prefer Java, because it handles loads better. The most popular frameworks for backend development in Java are Spring Framework and Hibernate. Some good beginner's tutorials are - 1. Spring framework2. Hibernate3. JavatpointJavaScript   It is a very popular choice for backend development, because on the frontend side JavaScript is the only choice. So, a lot of frontend engineers can take this choice to become Full-stack developers. Node.js   It allows developers to use JavaScript to write server-side code, through which they can write APIs. Actually, the API part can be done by numerous frameworks of Node.js out of which Express is widely used. The other popular framework is Fastify. Some good beginner's tutorials are - 1. Nodejs2. ExpressJs3. fastifyPython   Python is one of the most popular languages among developers and has been used in a variety of fields. The two most popular frameworks for Python are Flask and Django. Some good beginner tutorials are - 1. Flask2. DjangoC#   It is a very popular programming language which was developed by Microsoft and it has the power of C++. Its popularity increased once the .NET framework was released for backend development. As Microsoft is very popular in enterprises, the .NET framework is generally preferred in enterprises. A good tutorial to learn .NET is - 1. Dotnet2. Dotnet FrameworkGo  Go language which is also referred to as Golang, has gained popularity in recent years. It is used a lot in Backend programming and the two popular frameworks are Gin and Beego. DatabaseFor a Backend engineer, after making APIs with framework based on language, it's time to learn about Databases. Databases are used to store most of the things which we see in a web-app, from user login credentials to user posts and everything else. In the earlier days we only used to have one type of Database and that was Relational databases, which use tables to store data. Now we have two other categories also, one being NoSQL databases and the other In-memory databases. 1. Relational databases   Relational databases allow you to create, update and delete data stored in a table format. This type of database mostly uses SQL language to access the data, hence is also known as an SQL database. MySQL  It is one of the oldest databases and was released in 1995. It is an open-source database and was very popular in the 2000s with the rise of LAMP (Linux, Apache, MySQL, PHP) stack. It is still widely in use, but there are other popular Relational databases. A good tutorial to learn MySQL is - 1. MySQLPostgreSQL  PostgreSQL, which is also known as Postgres is also an old open-source Relational database, which was released in 1996. But it gained popularity recently, as it goes very well with modern stacks containing NodeJS and other backend technologies. A good tutorial to learn PostgreSQL is - 1. PostgreSQLOracle is the most popular and oldest relational database. It was released in 1979 and still remains the number one preference for enterprise customers. All the big banks and other organizations, run on Oracle databases. So, the knowledge of Oracle is a must in many companies for an Engineer. A good tutorial to learn Oracle is - 1. OracleMS-SQL  MS-SQL is also known as Microsoft SQL and is yet another commercial Relational database. It has got different editions, used by different audiences. It is also heavily used by enterprise users and powers a whole lot of big systems around the world. A good tutorial to learn MS-SQL is - 1. SQLServer2. NoSQL databases  NoSQL databases are also called non-SQL databases. The NoSQL databases mainly store data as key-value pairs, but some of them also use a SQL-like structure. These databases have become hugely popular in the 21st century, with the rise of large web-apps which have a lot of concurrent users. These databases can take huge loads, even millions of data connections, required by web-apps like Facebook, Amazon and others. Beside this, it is very easy to horizontally scale  a NoSQL database by adding more clusters, which is a problem in Relational Databases. MongoDB  It is the most popular NoSQL database, used by almost every modern app. It is a free to use database, but the hosting is charged if we host on popular cloud services like MongoDB atlas. Its knowledge is a must for backend engineers, who work on the modern stack. MongoDB uses json like documents to store data. A good tutorial to learn MongoDB is - 1. MongodbIt is a proprietary database service provided by Amazon. It is quite similar to MongoDB and uses key-value pairs to store data. It is also a part of the popular AWS services. A good tutorial to learn DynamoDB is-DynamoDBCassandra is an open-source and free to use NoSQL database . It takes a different approach when compared to other NoSQL databases, because we use commands like SQL, which are known as CQL (Cassandra Query Language). A good tutorial to learn Cassandra is - Cassandra3. In-memory databases   The in-memory database is a database, which keeps all of the data in the RAM. This means it is the fastest among all databases.  The most popular and widely used in-memory database is Redis. Redis  Redis (Remote Dictionary Server) is an in-memory database, which stores data in RAM in a json like key-value format. It keeps the data persistent by updating everything in the transaction log, because when systems are shut down their RAM is wiped clean. A good tutorial to learn Redis - RedisStorageStoring the data is an important part of any application. Although this is mainly DevOps territory, every backend developer should know the basics for the same. We need to store the database data and also the backend code. Beside this the frontend code must also be stored somewhere. Nowadays everything is stored in the cloud, which is preferred by individuals, startups and enterprises. The two most popular cloud-based storages are – Amazon S3 Azure Blob Storage Good beginner's tutorials for both areServices and APIsThese are theoretical concepts and are implemented by various services, but a backend engineer should know them and how to use them. Restful APIs  This is by far the most popular way to get data from a database. It was made more popular, with the rise of web-apps. We do GET, PUT, POST and DELETE operations to read, update, create or delete data from databases. We have earlier discussed different languages and frameworks, which have their own implementations for these operations. Microservices Architecture  In microservice architecture, we divide a large and complex project into small, independent services. Each of these is responsible for a specific task and communicates with other services through simple APIs. Each service is built by a small team from the beginning, and separated by boundaries which make it easier to scale up the development effort if needed. GraphQL  It is the hottest new kid in the block, which is an alternative to the Restful APIs. The problem with Restful APIs is that if you want some data stored in database, you need to get the whole data sent by the endpoint. On the other hand, with GraphQL, you get a query type language which can return only the part of the data which you require.  DevOps & DeploymentA backend engineer requires a fair bit of DevOps knowledge. So, we will next deep dive into the methodologies in DevOps. 1. Containerization & Orchestration   Containers are a method of building, packaging and deploying software. They are similar to but not the same thing as virtual machines (VMs). One of the primary differences is that containers are isolated or abstracted away from the underlying operating system and infrastructure that they run on. In the simplest terms, a container includes both an application’s code and everything that code needs to run properly. Container orchestration is the automatic process of managing the work of individual containers for applications based on microservice architecture. The popular Containerization and Orchestration tools are – Kubernetes Docker Good beginner's tutorials for both are -Kubernetes2. DevOps   DevOps is a set of practices that combine software development (Dev) and IT operations (Ops). It aims to shorten the systems development life cycle and provide continuous delivery with high software quality. The two most popular DevOps services are AWS and Azure. Both of them are cloud based and are market leaders. Both of these platforms contain a wide variety of similar services. AWS  It consists of over 200 products and services for storage, database, analytics, deployment, serverless function and many more. AWS is the market leader as of now with 33% of market share. The AWS certifications are also one of the most in-demand certifications and a must for frontend engineers as well as Backend engineers. Azure  Microsoft Azure is second in terms of market share of cloud-based platforms, with 18% of the market. It also consists of SaaS (Software as a Service), PaaS (Platform as a Service) and IaaS (Infrastructure as a Service) like AWS. 3. PaaS (Platform as a Service)   There are several smaller players, which provide Platform as a Service and are much easier to use than services like AWS and Azure. With these services you can directly deploy your React or other web-apps, by just hosting them on GitHub and pushing the code. These services are preferred a lot by freelancers, hobbyists and small companies as they don’t require investment in learning complicated services like AWS and Azure. The three most popular PaaS services are Digital Ocean Heroku Netlify 4. Serverless  Serverless computing is an execution model where the cloud provider (AWS, Azure, or Google Cloud) is responsible for executing a piece of code by dynamically allocating resources and only charging for the number of resources used to run the code. The code is typically run inside stateless containers that can be triggered by a variety of events including http requests, database events, queuing services, monitoring alerts, file uploads, scheduled events (cron jobs), etc. The code that is sent to the cloud provider for execution is usually in the form of a function. AWS Lambda  It is an event-driven, serverless platform which is part of AWS. The various languages supported by AWS Lambda are Node.js, Python, Java, Go, Ruby and .NET. AWS Lambda was designed for use cases such as updates to DynamoDB tables, responding to a website click etc. After that it will “spin down” the database service, to save resources. Azure Functions  They are quite similar to AWS Lambda, but are for Microsoft Azure. Azure functions have a browser-based interface to write code to respond to events generated by http requests etc. The service accepts programming languages like C#, F#, Node.js, Python, PHP and Java. Serverless Framework  It is an open-source web-framework written using Node.js. The popular services like AWS Lambda, Azure functions and Google cloud functions are based on it. CI/CD A backend developer should know the popular CI/CD (Continuous Integration/Continuous deployment) tools. These tools help to automate the whole process of building, testing and deployment of applications. Github Actions   It is a freely available CI/CD pipeline, which directly integrates to your GitHub based project and can be used in variety of languages. Jenkins  Jenkins is the most popular CI/CD automation tool, which helps in building, testing and deployment of applications. Jenkins was written in Java and over the years has been built to support over 1400 plugins, which extend its functionalities. Circle CI  Circle CI is also a CI/CD automation tool, which is cloud based and so it is different from Jenkins. It is much easier to use than Jenkins, but has a smaller community and lower user base. SecuritySecurity is an important aspect of any application. Most applications containing user personal data, like email etc, are often targeted by hackers. OWASP   The Open Web Application Security Project (or OWASP), is a non-profit organization dedicated to web application security. They have free material available on their website, making it possible for anyone to improve their web application security. Protecting Services & databases against threats   Hackers target databases of popular web-apps on a regular basis to get sensitive information about their customers. This data is then sold to the highest bidder on the dark-net. When such public breaches are reported, then it's a reputation loss for the enterprise also. So, a lot of emphasis should be given to Authentication, Access, Backups, and Encryption while setting up a database. The databases should also be monitored for any suspicious activities. Besides this the API routes also need to be protected, so that the hacker cannot manipulate them. Career roles Most of the companies hire Frontend developers, Backend developers and DevOps engineers separately. This is because most of the enterprise projects are huge, in which roles and responsibilities are distributed. But there is a huge demand for Full Stack developers in the startup sector in US and India. These companies need specialists who can get the product out as soon as possible with agile and small teams. Top companies hiringAlmost every company on the planet is hiring web-developers or outsourcing the development work. Since the past decade, the demand for developers has risen exponentially. The top technology companies which hire full stack developers are Facebook, Amazon, Apple, Netflix, Google, Uber, Flipkart, Microsoft and more.  The sites of each of these companies are web-apps (excluding Apple and Microsoft), with complex frontend and backend systems. The frontend generally consists of React or Angular and the backend is a combination of various technologies. The DevOps part is also quite important in these web-apps as they handle millions of concurrent connections at once.Salaries  The salary of a beginner Frontend developer in India starts from Rs. 300,000($ 3980) per year in service-based companies to Rs. 12,00,000($ 15,971) per year in the top tech companies mentioned above. The salary of a Beginner Full-Stack developer in India starts at Rs. 4,50,000 ($ 5989) per year in service companies to Rs. 12,00,000($ 15,971) per year in top tech companies. The salary for an entry level Frontend developer in USA is $ 59,213 per year and for an entry level Full stack developer is $ 61,042 per year.Below are some sources for salaries. web-developerfull-stack-developerfront-end-vs-back-endTop regions where there is demand There are plenty of remote and freelancing opportunities in web-development across the world. The two countries with most developers and top tech companies are USA and India. Silicon Valley, which is the San Francisco Bay Area, in Northern California, USA is the hub of technology companies.  The top city in India to start a developer job is the Silicon Valley of India – Bengaluru. The number of jobs is more than all the other cities combined and it also has a very good startup ecosystem. Almost all the big technology companies mentioned earlier and top Indian service companies are located in the city. After Bengaluru, the city where the greatest number of technology jobs are based is Hyderabad, followed by Chennai and then Pune. Entry PointsThe demand for web-developers is high and anyone with a passion for creating apps can become a web-developer. An Engineering degree is not mandatory to land a job as a web developer.  The most in-demand skill today and for the next 5 years is React and its ecosystem. So, if you know HTML, CSS, JavaScript and React, it is impossible to not get a job. Career Pathway  Most people start as an intern Front-end developer or Intern Full-Stack developer and in many cases Intern Backend developer. Many companies directly hire junior Frontend/Backend/Full-stack developers.  After that, the next step is the role of Senior Frontend/Backend/Full-stack developers. Many Frontend and Backend developers become full stack developers at this level, by learning additional technologies. Senior resources in Frontend/Backend/Full-stack can then go on to assume Team Lead roles. These people manage small teams in addition to being individual contributors.  After this a professional can become a Project manager, whose main responsibility is managing the team. Another role is that of Technical Project Manager, who manages the team and also has hands-on knowledge in Technology. The last role at this level is that of a Software Architect, who handles and designs big projects and has to look at every aspect of the technology to create the enterprise app. Generally Full-stack developers are preferred in this role, as they need to know all technologies. The highest career milestone is CTO or Chief Technology Officer, who handles all the technology teams and makes all technology decisions in a Technology company. Job SpecializationThere are some Full stack development specializations which I see nowadays in the industry. Full stack developers who work with React in the Frontend and Java in the Backend are in great demand. Similarly, developers who work with Angular in the Frontend and .NET in the backend are in great demand.How KnowledgeHut can helpAll these free resources are a great place to start your Frontend or Full-Stack journey. Beside these there are many other free resources on the internet, but they may not be organized and may not have a structured approach.  This is where KnowledgeHut can make a difference and serve as a one stop shop alternative with its comprehensive Instructor-led live classes. The courses are taught by Industry experts and are perfect for aspirants who wish to become Frontend or FullStack developers.Links for some of the popular courses & Bootcamps by KnowledgeHut are appended below-CSS3JavaScriptReactJSNodeJSDevopsFull-stack developer BootcampFront-end developer Bootcampback-end developer BootcampConclusion This completes our article on the Full stack developer journey by combining both the Frontend and backend roadmap. There are many people who become backend developers first by working on languages like Java and then go on to learn React to become full stack developers.  Again, many developers learn front-end development first with frameworks like React, and then become full stack developers by learning Node.JS. This path is easier for developers because both React and Node.JS use the same language which is JavaScript.We hope you have found this blog useful, and can now take the right path to become a full stack developer. Good luck on your learning journey!
9710
How to Become a Successful Full Stack Web Develope...

Full stack developer roles are among the hottest c... Read More

How To Install and Setup React Native on Mac

React Native Development Environment Installation:With the rapid growth of online websites, businesses, and the general ecosystem, it is crucial that website UIs load quickly on smartphones to encourage smartphone-based internet consumption. Facebook developed React Native from a need to generate UI elements efficiently, which formed the basis for creating the open-source web framework. Its native cross-platform capabilities allow usage for a wide range of platforms for application development, including Android, Web, Windows, UWP, tvOS, macOS, iOS, and AndroidTV. Microsoft also released a preview release in May 2020 that expanded the range of the React Native world, allowing desktop app development. React Native runs in the background of the destination device, and then communicates with the native platform via a batched asynchronous bridge. Its three main advantages are:It allows faster development due to its native natureThough it has a syntax styling similar to CSS or HTML, it is much quicker and efficientIt is flexible as it allows developers to write native code in various languages, including Java, Kotlin, and Swift.This article is about how to install and configure React Native CLI environment. First, we will learn how to install the framework, then check whether it works well and finally develop an app.PrerequisitesBasic computer proficiencyAn account with Administrative privileges on your computerAccess to the outlined documents and softwareA working internet connection to download the installation filesAudienceThis article guides first-time React Native users, junior developers, and developers with no experience with React Native. If curiosity nudged you to learn the framework due to the hype around React, then this is the guide you need.System requirementsSoftwareXcode version 11.3.1 or newer is required. Nodejs version 12 LTS or newer is required.HardwareMacOS requires a Mac device to operateRam - 4GBStorage - 10GBThese requirements ensure your tools run quickly and have enough storage for installation and development.System RequirementsReact Native requires macOS High Sierra (10.13) or higher to run efficiently.Installation through HomeBrew:HomeBrew is a package manager that helps you install and manage packages on Mac, and thus it will be essential to our installation process. You will install HomeBrew so that you can use it to install all the other tools necessary for React Native environment, including Nodejs, git, Watchman, and JDK.First download HomeBrew using the above link, then execute the command below in the Command Line Interface:brew—versionThe command verifies whether HomeBrew has been successfully installed and outputs the specific version installed as the following result shows:homebrew 2.1.7 homebrew/homebrew-core (git revision f487; last commit 2020-05-26)When the version is unavailable, you can install HomeBrew via this code:/usr/bin/ruby -e “$(curl –fsSL https://raw.githubusercontent.com/HomeBrew/install/master/install)”After installation, check whether HomeBrew has installed properly using the following command:brew--versionIf the software is well installed, the result will show the version and date as shown:homebrew 2.1.7 homebrew/homebrew-core(git revision f487; last commit 2020-05-26)NodejsReact Native is a JavaScript platform; hence it needs Nodejs to provide a JavaScript runtime.  Nodejs also provides essential tools such as a local webserver with live reloading, network tools, command-line tools, and web APIs.Use the HomeBrew command below to install Nodejs:brew install nodeCheck whether the installation is successful through the following command:node—versionIf the installation has occurred successfully, the Nodejs version will show up:V12.6.0Installation of Nodejs also includes installation of npm, the Node Package Manager. It would help if you had npm to help you install packages, libraries, and vital tools for your React development environment. To verify if npm is successfully installed, execute the following command:npm—versionIf the installation is successful, you will see the version as shown below:6.9.0WatchmanWatchman monitors the files and folders utilized by the framework and triggers specific actions if the files are modified. It would be best if you had Watchman for React Native to monitor source codes and rebuild them once they are changed.To install Watchman, execute the command below:brew install watchmanVerify installation through:watchman --versionif properly installed, the result will show the version as shown below:4.9.0React Native CLIYou need React Native CLI to develop the app by react-native. React Native CLI is installed by executing the npm command below:npm install --g react-native-cliCheck if the installation is successful using the following command:react-native --versionSometimes, users may get an error when using the npm install --g react -native-cli command. To avoid this, try entering sudo before this command, then enter your system password.If the installation is successful, you will see the version as shown:react-native-cli:2.0.1 react-native:n/a - not inside a React Native ProjectXcodeYou need Xcode for iOS app development, and you can download it via the above link. After installation, configure the Command Line Tools. Execute Xcode and go toXcode > Preferences > LocationsYou should see the Command Line Tools settings showing the version of Xcode as:Xcode 10.2.1 (10E1001)If the settings do not look like that, select the last version of the Command Line Tool from the dropdown menu.Go to components and select an iOS emulator, then download it (this is for those without iOS devices to run and test their apps on. It is also easier than using an actual device.)Move account tabs, select apple id, and input your apple id.Open Xcode and create a new project, name it anything, then close it. After project creation, click the root file and select "sign in and capabilities," then select your user id. Select your emulator and keep it ready for development.CocoapodsCoacoapods manages dependencies in iOS development, and thus it is necessary to develop an app by react-native.Install Cocoapods through the following command:sudo gem install cocoapodsVerify installation through:pod --versionif installation is successful, you can see the version as shown below:1.7.5JDKThe Java Development Kit is essential for the development of Android apps with react-native. Install JDK through the command below:brew tap AdoptOpenJDK/openjdk brew cask install adoptopenjdk8Verify installation through:java -versionIf you see the Java version as shown below, then Java has been successfully installed:openjdk version "1.8.0_222" OpenJDK Runtime Environment (AdoptOpenJDK)(BUILD 1.8.0_222-b10) OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.222-b10, mixed mode)JDK Installation also installs the Java Compiler, which can be verified by executing the following command:javac -versionIf the installation is successful, the following result shows up:javac 1.8.0_222Android StudioAndroid Studio is also an essential tool for developing an Android app using react-native.CONFIGURATIONOn the install type screen, select the custom option, choose your preferred theme, then select the performance (Intel R HAXM) option and Android Virtual Device option. Click Next, then leave the Emulator settings as they are, and click next again. Allow the standard installation to continue and click Finish to complete the process.ANDROID STUDIO SDK CONFIGURATIONClick Configure>SDK Manager and proceed to Android SDK Configuration.Select the Show Package Details option and select the following options:Android SDK Platform 28Intel  X86 Atom System ImageGoogle APIs Intel x86 Atom System ImageGoogle APIs Intel x86 Atom_64 System ImageClick ok to install the options selected.In the SDK Tools Window, select show package details >Android SDK Build Tools >Android SDK Build Tools 23.0.1.ANDROID STUDIO ENVIRONMENT VARIABLE CONFIGURATIONYou need to set environment variables to ensure the development environment fits your specifications.  Ensure that the ANDROID_HOME environment variable connects to your existing Android SDK to avoid complications.Open and include the following code to the ~/.bash_profile file or the ~/.zshrc file to add the environment variables:For .bash_profile users, use the following command:source ~/.bash_profileAfter configuration, restart the terminal, then execute the following command: adbThe correct result if all variables are successfully configured is:Android Debug Bridge Version 1.0.41 version 29.0.1-5644136 Installed as /Your Android SDK Directory Location/platform-tools/adbGit1.You can also use git, which comes with Xcode. However, if its unavailable, run the code below:brew install gitgit is a substitute for the Android Studio development environment.Gradle DaemonSometimes you may need to modify the java code, in which case, your development speed will be affected. Gradle Daemon is a tool that manages these changes to speed up your development.Other Installation MethodsExpo CLIExpo CLI is a tool built to install and manage react-native frameworks. However, its unsuitable feature is that it has numerous native features, which makes building an app tedious and also makes the app size more extensive than it needs to be. Additionally, incorporating elements in an app that are not available in Expo CLI is difficult, making the tool unsuitable for developers. Despite that, Expo CLI has many useful native tools, unlike React Native CLI, such as geolocation, camera, the microphone that can come in handy for most application needs. Expo CLI is a much easier route than the react-native CLI route.The installation process is as follows:1.Install the Expo CLI command line utility using:Npm install –g expo-cli2.Run the command below to create your first project:expo init my app3. Browse to the directory with the following command in the terminal:4. Finally, run the projectExpo start5. A development environment server will be started by these commands. Running the app requires installing the Expo client app to your device (iOS/Android) then connecting it to your computer. Android requires scanning the QR code on the terminal to authenticate the project, while iOS requires QR code scanning using the camera app. On the Android (emulator/real device), use the following command to initialize the app:npm run android6. While on the iOS emulator run:npm run iosExpo has docs that you can reference for solutions or even utilize the Expo Forums created for the Expo community to ask questions.Expo is mostly best suited for beginners as it does not include the use of native code thus cannot be used to develop complex applications with custom components.TestingProject structureReact Native project structure consists of a project directory with configuration files such as package.json, app.json, .watchman.json at the root; separate Android and iOS folders; a _tests_ folder with validation tests for the project; a nodes_module for housing smaller app modules; and an index.js file that maps the application and serves as the initialization point of the application. package.json  specifies project dependencies and versions, while app.json contains the app name.The npm (node package manager) manages the node_modules folder, which stores all the project library dependencies. You should avoid modifying the files present in the folder since alterations performed cannot be assured to be stable from updates/installs. Assets in the public folder are to be shared publicly. The src folder contains all development work by the developer, including components and source codes.Developing an app1. First, you need to lock the version you build with to ensure the app still works even after updates, using the following command:npm config set save-exact=true2. Create a native project through the command:react-native init AwesomeProject cd AwesomeProject react-native run-iosYour new app will run successfully in the emulator.3. In iOS, execute the command below:cd SampleApp #react-native run ios npm run iosThe react-native app will show up on the emulator.4. On Android, run the following command:cd SampleApp #react-native run-android npm run androidYour Android emulator will output:Welcome to ReactSecond App VerificationHello World is a simple program for most development environments. Open index.ios.js for iOS or index.android.js for Android, then proceed to delete everything between the tags .  Write Hello World and execute the emulator.The result will be Hello World on the screen.Modifying Your AppAfter successful testing, you can modify your app through the following steps:Open index.ios.js or index.android.js and edit some files.Click CommandX + R in the iOS Emulator and reload to see changes.Potential issuesYou might encounter problems while installing Cocoapods or React Native CLI - the most probable solution is entering a sudo command before the installation command, which will prompt you for your system password. Input the password, and your installation will go through just fine. You might also get this result [Broken AVD system path. Check your ANDROID_SDK_ROOT value]. Check if you installed android -sdk using homebrew; if you did, then uninstall it through the following command: brew uninstall android-sdk Another error is No ANDROID_HOME which means the bash files do not point to the ANDROID_HOME path. You can correct this through the following steps:Open and add the following code to the ~/.bash_profile file or the ~/.zshrc file to add the environment variables:#export ANDROID_HOME=$HOME/Library/Android/sdk export ANDROID_HOME=android SDK directory location/ Android/sdk export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/tools/bin export PATH=$PATH:$ANDROID_HOME/platform-toolsFor .bash_profile users, use the following command:source ~/.bash_profileThen proceed to verify the correction using the following code:echo $ANDROID_HOME // default: /Users//Library/Android/sdkAndroid Emulator won't run from Android Virtual Device Manager – Android Studio rarely shows an error that may occur in the Android Device Emulator; thus, you need to utilize the command line and run the commands below to check the name of the Android virtual device:Avdmanager list avdThen runEmulator –avd Wait for the device to boot up, then run your app in the emulatorReact-native run-androidYour app should run successfully.No Connected devices- you should run the following commandReact-native run-androidWrong Android emulator – you need to find the right emulator using the following code:find - -name emulator –type f /Users//Library/Android/sdk/emulator // this /Users//Library/Android/sdk/tools/emulator // not thisRestart the terminal and verify the error is gone.Avdmanager not found- write ~/.bash_profile, then add the following code afterwards:PATH=$PATH:$ANDROID_HOME/tool s/bin export PATHthen runsource ~/.bash_profileQuit and restart the terminal, then run the tools.Uninstallation procedureSometimes you might need to uninstall and wipe off the whole react-native environment due to issues such as a broken development environment which can be caused by misusing commands or assigning storage to variables incorrectly.  To do so efficiently, use the uninstall command together with the -g flag, then include the scope if the package is scoped.  A good example is as follows;npm uninstall -g react-native-cliornpm uninstall for scoped package usenpm uninstall As our installations have a package.json file, you might need to remove a package from the dependencies in that file. Use the following commands to effect these changes:npm uninstall --save or the following for a scoped packagenpm uninstall --save You will also need to verify if the uninstallation is successful through the following commands on macOS:ls node_modulesThis command ensures the node_modules do not contain a folder for the uninstalled files.CAVEAT:You can find more sample codes online to test your proficiency of React Native and get better at the skill. React Native is based on MIT License that grants Facebook copyright for portions of React Native for macOS extension derived from React Native. Remember to only download software from the official stated sites to avoid downloading compromised, malware-ridden software that can cripple your computer. If your computer shows any warning while executing any of the above steps, ensure to verify the software, ask an expert or ask on online community platforms. After completing and understanding all these steps successfully, you are now officially a beginner. You can proceed to the next stages of React Native app development until you become an expert. Some of the most significant areas you need to look at afterwards include animation, command-line instructions, components, shareable APKs, custom fonts, debugging, ESLint, images, layout, HTTP requests, Firebase integration, listview, native modules, and routing.The guide presented has shown how to install React Native through various methods and why the tools stated are required, then showed examples of apps and finally the uninstallation procedure. Tooling and development in React Native are simple, and the learning curve is short, making it an ideal framework for web developers.  The growth of internet consumers, cross-platform development, and the whole of the internet ecosystem is an excellent catalyst for React Native to grow in popularity among developers. It offers them faster development speed while offering internet consumers speedier loading times and more beautiful website UIs.  As you have seen, React development is simple; hence it should convince you to get started and launch your own apps within a short period. Being a new but highly applicable language, React Native holds a lot of opportunities, career wise and development wise. There are also numerous React Native platforms on the internet that can help you solve challenges you might face in development. Keep coding and have fun!
8833
How To Install and Setup React Native on Mac

React Native Development Environment Installation:... Read More

How to Install MongoDB on a Mac

MongoDB is one of the most popular unstructured database management systems that can store a high volume of data. It is a document-oriented database system that belongs to the family of NoSQL (non-SQL). Here the data and records are stored as documents that behave more like JSON objects. Documents are a combination of key-value pairs that form the basic unit of data in MongoDB. This database system came into action in mid-2000.What is NoSQL and why should we use NoSQL?NoSQL stands for Not Only SQL or non-SQL and is an unstructured database that helps store and retrieve data. In the year 1998, Carl Strozz introduced NoSQL. It models the data by means other than the tabular relations. It means such databases do not have a fixed schema, but are intended explicitly for the distributed data that demands humongous data storage. We use NoSQL databases for real-time web apps, mobile apps, big data, etc. Websites like Google, Twitter, Amazon, Facebook, Instagram, etc., collect terabytes of data every day.Earlier, web applications were simple and did not generate such huge amounts of data. But with the advent of big companies like Facebook, Google, Amazon, etc., huge volumes of data are generated, because of which NoSQL databases have become popular. Traditional RDBMS (like SQL) uses simple queries to store and retrieve textual data. But NoSQL database management systems embrace a wide range of file systems storing structured, unstructured, semi-structured, and polymorphic data.Features of NoSQLNoSQL databases do not follow the relational model. They are schema-free, or they do not follow any specific schema. NoSQL renders heterogeneous data structures (graph, tree, column family, key-value pair, document, etc.) on the same domain. Data is not stored flat in rows and columns (table). NoSQL does not demand data normalization and object-relational mapping. NoSQL does not demand setting up complex concepts like joins, referential integrity, ACID properties, etc. Who should use MongoDB?Developers who want to deal with structured, semi-structured, or unstructured data need to use MongoDB for their applications. Those who are into Big data analysis can also use MongoDB. Again, if an application's data needs agility, scaling, and high performance, MongoDB is the best solution.   It supports a broad spectrum of use cases, from real-time exploratory and predictive analytics to parallel data processing. MongoDB can provide high-performance data storage even when spread across multiple servers.PrerequisitesSoftware Requirement:macOS 10.13 or later MongoDB 4.4 Community Edition (we will show the download procedure later) Install Xcode Command-Line Tools: Homebrew demands to install the Xcode command-line tool from Apple's Xcode before using it. To install Xcode, you have to run the following command in your macOS Terminal:  xcode-select --install Homebrew package manager: By default, macOS does not incorporate the Homebrew package. You can install Homebrew using the documentation given on their official website (https://brew.sh/#install).  Hardware Requirement:Intel Processor / Apple M1 Processor 4 GB RAM preferred Installation StepsInstall Manually without BrewStep 1: Let us now download MongoDB. For this, open your web browser and type: google.comStep 2: From Google search, type: MongoDB and hopefully, the first link the search throws up would be the MongoDB link. From here, we have two ways of installing MongoDB. Follow these steps to install using the macOS terminal.Step 3: Go to mongodb-community Select the version, platform, and package. Make sure you choose macOS as the platform and 'tgz' as the file format and click the download button.Step 4: Once the tgz file gets downloaded, go to the macOS terminal to extract it. Step 5: Mostly, your MongoDB will get downloaded in the Downloads folder. For this, type the following command in the terminal:cd Downloads/ ls tar xzf mongodb-osx-ssl-x86_64-4.4.tgz Step 6: Now, we have to move the MongoDB folder to our local binary storage. sudo mv mongodb-osx-ssl-x86_64-4.4 /usr/local/mongodbThis will ask for your system password. Provide the password. You can change the directory to /usr/local/mongodb and see whether all the files exist or not using the ls command. Note that this step is optional. To change the directory, type the command cd /usr/local/mongodb Next, you have to create the db folder. By default, MongoDB writes or stores the data in the folder called data/db. The command for this will be sudo mkdir -p /data/db The -p flag will allow us to create the directory structure. Now, to check whether this path and directory have been created or not, we use the command: cd /data/dbTo check whether we are on the right directory or not, just type the command: pwdFor changing the permission, you need to know your username first. To know your username, type the command: whoamiNow change the permission of this directory. To do this, the command is: sudo chown /data/db Finally, you are eligible to directly run the mongo process.  Install using Brew –If you want to install MongoDB through Homebrew manually, follow these steps – Step 1: Homebrew helps in installing and managing applications on MacOS. If you haven't downloaded or installed Homebrew, then click the link (https://github.com/mongodb/homebrew-brew) to download the official Homebrew formula for MongoDB, by running the command in your macOS Terminal:  brew update  brew tap mongodb/brew Step 2: Once the Homebrew package resides in your system, you can download MongoDB using brew. Step 3: Type the following command in your macOS Terminal: brew install mongodb-community@version-numberStep 4: This installation will add the following binaries: The mongod server The mongo shell The mongos sharded cluster query router Step 5: The installation will take a few seconds. Once done, you can create a directory to store MongoDB data using the following command. sudo mkdir -p /data/db Step 6: Now, you have to note that your data directory should have the appropriate permissions. To do this, execute the command: sudo chown -R `id -un` /data/db Step 7: This will ensure that the data directory is ready and has all the proper permissions. Step 8: Apart from that, the MongoDB installation will produce the following files and directories at the locations given below – Intel Processors Apple M1  Log directory/usr/local/var/log/mongodb/opt/homebrew/var/log/mongodbConfiguration file/usr/local/etc/mongod.conf/opt/homebrew/etc/mongod.confData directory/usr/local/var/mongodb/opt/homebrew/var/mongodbStep 9: Let us now run the MongoDB community Edition. You can use the brew command to run MongoDB as a macOS. A manual procedure is needed to run MongoDB services on macOS. To execute MongoDB daemon, which resides by the name mongod (process), use the following command: brew services start mongodb-community macOS will run this process as a macOS service. Step 10: For stopping a mongod process running as a macOS service, apply the following command: brew services stop mongodb-communityStep 11: For running MongoDB in the background manually and listening for connections on a given port, use the following command - For Mac systems with Intel processors: mongod --config /usr/local/etc/mongod.conf --fork For Mac systems with Apple M1 processors: mongod --config /opt/homebrew/etc/mongod.conf –fork Step 12: Next, verify your MongoDB version. To do this, type the following command: mongo –version Step 13: The command line will display the installed version of MongoDB on your Mac system. Developers recommend using the newest version of libraries and software whenever feasible. It will keep you away from any compatibility issues with client-side applications. Step14: You can view the installation list by typing the command: mongodb Step15: Use the command mongod --config /usr/local/etc/mongod.conf to start the MongoDB Step 16: To connect to mongodb service, type the command: mongo Step17: Use the ‘show dbs’ command to see all databases. You can learn more about the working of MongoDB and become an expert NoSQL database administrator by joining the course mongodb-administrator. This course covers features of MongoDB 4.0 and future releases. Uninstall MongoDB on macOS X –Uninstalling MongoDB from your system will entirely remove MongoDB along with its associated files. Before uninstalling MongoDB, check whether any mongo service is running by using the command: launchctl list | grep mongo If any running process exists before uninstallation, you should stop or kill it. To kill all the processes related to mongod, use the command: pkill -f mongod The command to uninstall MongoDB from your system is: If installed via brew: brew uninstall mongodb-communityOr, if installed manually you can simply delete the folder: rm -rf If you have a separate folder for the database, use the command to remove that database directory: rm -rf /data/db MongoDB is the leading NoSQL, document-based, open-source database system. It is a cross-platform system - licensed under the Server-Side Public License (SSPL). Due to its broad spectrum of features and benefits, it became popular very quickly. Hopefully, this article has helped you understand the basics of installing MongoDB in your Apple system.   In this article, we have walked you through the two ways to install MongoDB in a macOS. Also, this article explicitly talked about installing MongoDB in Apple systems with Intel processors and with Apple M1 processors. So, you can navigate this article as per your system. You can learn more about MongoDB installation and join the course from mongodb-administrator.
8995
How to Install MongoDB on a Mac

MongoDB is one of the most popular unstructured da... Read More