Author Archives: Web Development Tutorial

ASP.NET Core Tutorial for Beginners

With this article today, we are going to start a tutorial Series on ASP.NET Core for developers having knowledge of existing Microsoft web technologies (including ASP.NET Web Forms, ASP.NET MVC, ASP.NET Web API etc.) but wanted to start the new ASP.NET Core from the very beginning. Here we will start with basic core concepts and further add more practical articles to this ASP.NET Core Tutorial Series.

ASP.NET Core Tutorial – Start as a Beginner

ASP.NET Core 1.0 or ASP.NET 5 – MVC6 is a re-write version of ASP.NET 4.6 with following key features:

  • ASP.NET Core is Open-Source.
  • It’s a framework that is Cross-platform, means can run on Linux or MacOS. Before that .NET Framework (as a whole) can only be used in Windows platform. This is considered as a huge enhancement.
  • Ideal for building Web applications, Iot apps and mobile backends.
  • Cloud ready configuration.
  • ASP.NET Core 1.0 is smaller in size as compared to ASP.NET 4.6 framework as it runs on stripped down version of .NET Framework i.e. .NET Core 1.0.ASP.NET CORE Tutorial

At a broader view, we must be clear that:

  • ASP.NET 5 is now renamed as ASP.NET Core 1.0
  • .NET Framework 5 will be known as .NET Core 1.0 and
  • Entity Framework 7 will be renamed to Entity Framework Core 1.0.

Key Features of ASP.NET Core:

Key Features of ASP.NET Core

Cross Platform Support:

.NET Core is Cross-platform web framework, that is more modular and cloud optimized, can be Build and Run on Windows, Mac, Linux for modular development stack.  The libraries are modular and distributed via NuGet packages. It was architected to support an optimized development framework for web application that are deployed to the cloud. Its libraries are standard that minimizes allocations and the overall memory of our system.

Open Source:

ASP.NET Core is fully open source, developed with the community and with Microsoft’s support. Not only the source code but documentation is open source available in github and docs.asp.net respectively. We developers can download, inspect, modify and enhance it. Whatever the good work we do as a ASP.NET Core community member, we can forward it to Microsoft for approval.

Performance:

Performance has always been an issue for Microsoft .NET and to overcome this issue they introduced new managed web server i.e. “Kestrel” with .NET Core. This new Web Server written in C# is designed from scratch to be the fastest available .NET Server.

Microsoft is very successful in achieving it’s goal with respect to performance as ASP.NET Core now lands among the top in the list. Below is a comparison of ASP.NET Core with other technologies:ASP.NET Core Performance

https://twitter.com/davidfowl/status/700139258279899137

Built-In Dependency Injection:

Dependency Injection is a technique used normally to achieve loose coupling between objects and their dependencies. Using DI, an object can be used with other services without having much details about it. Dependency Injection is now built-in with ASP.NET Core framework as a Dependency Injection service container with minimal features.

Single/Unified Programming Model for MVC and Web API:

Microsoft has unified ASP.NET MVC and Web API into single programming Framework, removing the overlap between these different frameworks. Unified Framework simplifies the development process by introducing a unique namespace i.e. Microsoft.AspNet.Mvc. Also making integration easier with client-side frameworks like Grunt/Bower and simplifies adding cross-cutting concerns with controller.

You can follow below for more helpful material regarding related technologies here:

8 Steps to develop RESTful API using Express and MongoDB

In this MEAN Stack Tutorial, we are going to develop a RESTful API using Express.js and MongoDB. We will follow a step by step approach to make it easier for readers in developing their first RESTful API on MEAN stack.

Following are the steps to build the API:

Step 1: Initialize the Project

  • Create a folder with the project name such as todoapp.
  • Open command prompt window on the project folder.
  • Run the following command:
    This command will create a package.json file with following details:

    MEAN Stack Tutorial

Step 2: Install Express

  • Install express with following command:

Step 3: Install Express Generator

  • Install express-generator using following command

Step 4: Create the Project

  • Use the following command to create the express project

    This will give the following output

Step 5: Install Dependencies

  • The package.json file will look like as following:

  • Install all the dependencies using following command:

Note: You can find more helpful details on MEAN Stack especially AngularJS 1.x & AngularJS 2 here.

Step 6: Install HBS, MONGO

  • Install mongo  using following commands:

Step 7: Run Mongo

  • Run mongod.exe it will start the MongoDB.Run MongoDB
  • Connect to todoapp databse using following command:Mongo Exe

Step 8: Create Mongo Service and Connect to Database

  • On app.js file add mongo database as following:
  • Create a middleware to connect to database
  • Create a new router for todo in ‘routes/todo.js’ file
  • In app.js add the router for initialization
  • Create a new form template inside views folder with the name ‘new_todo.jed’
  • Run the app using the following command
  • From browser if we run http://localhost:3000/todos/new, we can view the New todo page as following:ExpressJS Tutorial
  • Next step is the write the method that will be executed once the add-todo form is submitted in routes/todos.js file add the following router method.
  • Now submitting the form will redirect to /todos/add-todo route and make a POST request. The todo will be saved in the database.

Hopefully, this MEAN Stack tutorial will serve as your first RESTful API using ExpressJS with MongoDB. We will come with more detailed technical tutorial on related technologies soon. Keep in touch :-)

Top Related Technical Articles:

Top Express.js Interview Questions and Answers

This Web Development Tutorial is last in series of MEAN Stack Interview Questions and Asnwers series covering ExpressJS. Previously, we have covered all other areas including AngularJS, AngularJS 2, NodeJS and MongoDB. You can follow the below link to get updates about all MEAN Stack development articles and tutorials covered so far as well as published in future.

MEAN Stack ExpressExpress.js is another famous JavaScript Framework that gained a lot more popularity in recent years. We will follow the same strategy to explore all various topics by following Interview Question and Answer pattern.

Express.js Interview Questions PDF version will be available later for download.

Express.js Interview Questions List

What is Express.js? What are core features of Express framework?

What is Express.js?

Express.js is a light-weight node.js based web application framework. This JavaScript framework provides a number of flexible and useful feature in order to develop mobile as well as web application using NodeJS.

ExpressJS Features:

Following are some of the core features of Express framework −

  • Set up middlewares in order to respond to HTTP/RESTful Requests.
  • It is possible to defines a routing table in order to perform different HTTP operations.
  • Dynamically renders HTML Pages based on passing arguments to templates.
  • Provides all the feature provides by core Node.js.
  • Express prepare a thin layer, therefore, the performance is adequate.
  • Organize the web application into an MVC architecture.
  • Manages everything from routes to rendering view and preforming HTTP request.

Back to top

How to setup an Express.js App?

We can follow the below step by step approach to set up an Application using ExpressJS Framework.

  • Create a folder with the same name as Project name.
  • Inside the folder create a file called package.json.
  • Open command prompt on the project folder and run following command.
    This will install all the libraries defined in package.json inside dependencies{} and the libraries are installed in node_modules folder.
  • Create a file called server.js.
  • Create a folder called ‘routes’ inside the project folder.
  • Create a file inside ‘routes’ folder called index.js.
  • Create a folder called ‘app’ inside the project folder and create a file inside ‘app’ folder called ‘index.html’.ExpressJS Setup Tutorial
  • Create a index.html file.
  • Open command prompt on the project folder and run following command.
    The output would be
  • Now open a browser with link http://localhost:3000, the output would be:ExpressJS App Tutorial

Back to top

How to config Angular 2.0 Frontend in Express.js Application?

With the Angular 2.0 the MEAN stack has a huge changes. These are the following steps to create an application using MEAN stack.

  • Install Node.js.
  • Create an express application using express generator.
  • Use the view engine as ejs, therefore, install ejs.
  • Set view engine in app.js.
  • Set the static folder.
  • Create the config file inside public folder following the Getting started from angular.io.
    package.json

    tsconfig.json

    typings.json
    system.config.js
  • Now run ‘npm install’ command to install all the necessary dependencies.
  • Change the ‘views/index.html’ folder with the following code.
  • Create an app.component.
  • Add the template.
  • Create Angular App module in ‘public/app/app.module.ts’.
  • Now on the browser it would look like:Getting Started ExpressJS
  • Similarly add other angular module to the angular app.

Back to top

Explain Routing in Express.js in details?

  • Create a file called routes.js  containing all the routes of the application.
  • Create a file called MemberController.js.
  • Create a file called MemberService.js and DatabaseService.js would be created.
  • In server.js add the following code:
  • Now any  of the route defined in routes.js can be accessed.

Back to top

Explain Logging in Express.js? Give a practical example to demonstrate?

With Express 4.0, the application can be generated using express-generator and it includes morgan as the logger:

  • Create express app using express generator.
  • The middleware in app.js is already added.
  • Create the local middleware.
  • Otherwise, If logging is need to be added to a log file.
    Add fs to app.js
    Add the file
    Create the middleware
  • Make sure logging will be enabled only in development environment.
  • Now if we run from the browser we can see that every request is being logged.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

NodeJS Course
Take this Course Online Now

How to config properties in Express Application?

In an ExpressJS Application, we can config properties in following two ways:

With Process.ENV?

  • Create a file with name ‘.env’ inside the project folder.ExpressJS Config Properties
  • Add all the properties in ‘.env’ file.Environment File in ExpressJS
  • In server.js any of the properties can be used as:

With RequireJs?

  • Create a file called  ‘config.json’ inside a folder called ‘config’ inside the project folder.
  • Add config properties in config.json.
  • Use require to access the config.json file.

Back to top

How to allow CORS in ExpressJS? Explain with an example.

In order to allow CORS in Express.js,  add the following code in server.js:

Back to top

How to redirect 404 errors to a page in ExpressJS?

In server.js add the following code to redirect 404 errors back to a page in our ExpressJS App:

Back to top

Explain Error Handling in Express.js using an example?

From Express 4.0 Error handling is much easier. The steps are as following:

  • Create an express.js application and as there is no built-in middleware like errorhandler in express 4.0, therefore, the middleware need to be either installed or need to create a custom one.

Create a Middleware:

  • Create a middleware as following:

Install Error Handler Middleware:

  • Install errorhandler.
  • Create a variable.
  • Use the middleware as following:

Back to top

How to implement File uploading and downloading with Express?

Below we have explained the process to upload as well as download a file with ExpressJS App.

Upload File in Express.js:

  • Install formidable.
  • Add the following code in server.js in order to upload a file.
  • Update the index.html as following:
  • On Browser run ‘http://localhost:3000’.

Download File in Express.js:

  • Add the following code in server.js.

Back to top

How to enable debugging in express app?

In different Operating Systems, we have following commands:

On Linux the command would be as follows:

On Windows the command would be:

From Webstrome IDE

Back to top

Explain in detail a middleware w.r.t Express.js?

What is Middleware?

Express app is usually a web framework consists of middleware and router.  Therefore, an express application works through a series of middleware functions.

Middleware is:

  • One or a series of callback function that sits on top of the actual request handler and have the exactly same parameter as actual request.
  • A series of functions are invoked by the router layer of express app before the final request handler.
  • A series of functions those are invoked in order. This means the order in which they are written/included in a server.js file, are the order in which they are executed, given that the route matches.
  • A function that receives the request and response objects of an HTTP request/response cycle.
  • A function that can modify the request or response object before sending them to next middleware function in the series.
  • It may update the response object or discontinue the chain if necessary.
  • A function with a signature of (req, res, next), for example:

Here in this example, the next() continue the chain of the series of functions known as middleware. next is the third parameter in the middleware function and need to be explicitly called at the end of the operation executed inside the function as, express has no way to understand when the function has come to end of execution of current operation and the next method in the series need to be invoked, therefore, next() method need to be called.

The following image can explain a middleware code:What is Middleware

What Middleware does?

Middleware functions can be used in order to perform the following tasks:

  • Execute any operation coded in the method.
  • Update the request and the response objects.
  • End the request-response cycle. For example, if there is any exception is thrown, instead of calling the next method in the series of middleware, it can end the chain.
  • As middleware in express is usually a series of methods / functions. Middleware is responsible to call the next middleware function in the series.
  • The flow of middleware could be as following:Types of Middleware

Back to top

What are the different types of middleware?

Types of Middleware?

  • Application-level middleware
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

Application-level middleware:

This kind of middleware method is bind to the app Object  using app.use() method. For example:

In this example, a middleware functions that prints the current time, has been mounted with app Object using app.use() method. However, this middleware function has neither mount path nor mount point. It is just executing a single instruction and not connecting to router.

However, in the second example,the middleware has a mount path ‘/book/:id’. Therefore app.use() accepts an optional path parameter just like the app.get() and other routes as following.

Now in the third  example of application-level middleware has both mount-path and mount-point and instead of a single method , this example shows  a series of middleware functions those are invoked one after another.

Another way to use application-level middleware is to call app.METHOD() . However, the only difference between app.use and app.get is that /books to an app.get(),would only be invoked when someone visited exactly /books route, however, when /books is a parameter to to app.use(), any request that starts with /books  will invoke the app.use function. For example,

Router-level middleware:

Router-level middleware can be used by using router.use() or router.METHOD().

OR

Error-handling middleware:

Unlike application-level and router-level, error-handling middleware takes four argument, for example:

Built-in middleware:

Starting with version 4.x, there is only one built-in middleware is express.static.

This middleware function is based on serve-static, and is responsible for loading static assets such as HTML files, images, and so on.The function signature is:

Here root is the directory name and options are several options. The following table describes the properties of the options object, see express.static.

Property Description Type Default
 dotfiles  Determines how the files or directories that begin with a dot “.”are treated.  String  “ignore”
 etag  Enable or disable etag generation.  Boolean  true
 extensions  If a file is not found, search for files with the given extensions and load the first one found. Example: [‘html’, ‘htm’].  Boolean  false
 fallthrough  Let client errors fall-through as unhandled requests, otherwise forward a client error.  Boolean  true
 index  Sends the specified directory index file. Set to false to disable directory indexing.  Mixed  “index.html”
 lastModified  Set the Last-Modified header to the last modified date of the file on the OS.  Boolean  true
 maxAge  Set the max-age property of the Cache-Control header in milliseconds or a string in ms format.  Number  0
 redirect  Redirect to trailing “/” when the pathname is a directory.  Boolean  true
 setHeaders  Function for setting HTTP headers to serve with the file.  Function

Third-party middleware:

There are a number of third party middleware, such as body-parser.mongoose, morgan and so on. These can be installed by using command:

And they can be loaded using requires and used later. For example:

How  to create a Middleware?

To create a middleware that will print the current time and save a book to database and render a message.

  • First create the method for logging current time.
  • Use the middleware function as an application-level middleware.
  • Create a middleware to connect to DB.
  • Save a book as the next in middleware.
    Every method will be executed one after another in order.

Back to top

That is all we have about Express.js Interview Questions and Answers. Next we will come up with more related Web Development related Interview Questions and Answers. You can follow the below given other technical interview questions and answers to improve your technical skills.

Top Technical Interview Questions and Answers Series:

Advanced MongoDB Interview Questions

This MongoDB Tutorial is Part 2 in series of MongoDB Interview Questions. In this technical interview questions part, we will learn about more advanced topics related to MongoDB as NoSQL database. If you haven’t gone through the previous part, we will highly recommend to go through the previous one first and then move to these advanced Interview questions or topics on MongoDB. MongoDB Interview Questions

Getting Started MEAN Stack Tutorial Series

We already have covered other components of Full Stack JavaScript by cover the followings:

MongoDB Tutorial PDF version will be available later for download.


MongoDB Interview Questions Tutorial – From Beginner to Professional

What is difference between Replication and Sharding? Can we achieve these two with MongoDB?

Replication:

Replication as the name suggests, is the process of synchronizing data on multiple servers. In other words the copy of data will be maintained on different servers. Replication gives us the surety that the data is available on more then one server. This increases the availability of data, since data will be available on more then one server. It helps us to fight against data loss since in case of fail-over of server data will be available on other servers.

With replication in place there will be no data loss, also the availability of data will be 24/7, we don’t need to worry about downtime since there are replicas and we can use any of the server to read. Data will be read scalable, that means since there are more than more copies of same data, app can use any server instance to read.

Replication with MongoDB:

In mongodb replication is achived by replica sets. A replica set is a group of mongodb instances that have the same data. In replica set one node is primary node that receives  all data and primary node then replicates the data to secondary nodes. There can be only one primary node in replica set.

A replica set is a group of two or more nodes, within which there will be one primary node and other nodes will be secondary nodes. Data is typically replicated from primary node to secondary nodes. At the time of failover a new primary node is automatically selected and connection is established to the new primary node.Replication in MongoDB

The above diagram demonstrates how replication is performed in MongoDB.

Lets see how replica sets are created?, below is the syntax for the same:

We need to shutdown the mongodb instance first and then again execute this command with the replica set name. –replset is the command flag that is need to start mongodb with replicaset.

Once server is started, from mongodb client we need to fire a command that is rs.intiate() to initiate a new replicaset.

Sharding:

Sharding is the concept of splitting data across multiple machines. It basically splites data among smaller datasets and stores across machines. At times querying against huge data set needs a very high cpu utilization. To tackle this situation Mongodb comes up to a concept of sharding, which actually splits the data across multiple machines. This can be a large collection of shards but logically all shards works a collection.

Components:

Components of a shard typically include the following:

  • Shard: Shard is a mongodb instance which holds the subset of data.
  • Config server: Config server is also a mongodb instance which holds information about the mongodb instances which holds shared data.
  • Router: Again a mongodb instance which is responsible for directing the commands sent by server.

This is all about Replication and Sharding in MongoDB.

Back to top

In RDBMS there are functions available for min, max, count etc. for aggregation, are there any such functions available in MongoDB to achieve aggregation, explain each aggregation function with example?

Aggregation is the concept of processing data records and return aggregated result. Like RDBMS aggregation is possible as well in MongoDb as well. Ofcoures here we will not be using select count(*) type of syntaxes but the same will be achieved by functions available in MongoDb. Aggregation group multiple records/documents from a collection and perform operation on these records and return a computed result. In MongoDb aggregate()  method is used to perform aggregation. Below is the syntax for the same:

Lets add some records in the collection ScienceBooks, with following schema:

To demonstrate this, we have created a records file with some data and imported to database. Below is the content of the file:

Lets import this file now and see the output:Sharding in MongoDB

The code above demonstrates the import and find from books collection:

Count():

Now our books collection which is in BookStoreDB has few records , with which we can play around through aggregation :

Lets suppose we want to find how many books are in Chemistry Category and how many in ComputerScience category, similar to select Category, count(*) from books group by Category;Aggregation Function in MongoDB

min() :

Now lets suppose we want to get the minimum price for each category, below is the code for the same:

Executing this code will result in the minimum price of book for both the categories.

max():

Similiarly suppose we want to get the maximum price for each category, below is the code for the same:

Executing this code will result in the maximum price of book for both the categories.

sum():

Now if we want to have the sum of price of all books available in our book store, below will be the code for the same:

These all the basic aggregation RDBMS functions that MongoDb also supports and with the code examples.

Back to top

What is the composition/structure of ObjectId in MongoDB? Explain in detail each composing element.

ObjectId in MongoDb plays a very special role. It associates with _id field, and MongoDb uses objectid as the default value of _id in documents.

As we know Object is of type BSON. Object is 12 byte bson type data structure. The composition/structure of ObjectId is as follows :

  • The first 4 bytes represents the seconds since last unix time.
  • The next 3 bytes after first four are the machine identifier.
  • The next 2 bytes after the machine identifier are the process id.
  • The last 3 bytes after machine identifier is some random counter value.

This represents the object id structure in a whole. To generate object id, MongoDb provides function as objectId(), syntax for the same is below :

Lets take example of creating ObjectId:

The above statement will return the unique hexadecimal string containing object id as below:

We can also provide some unique hexadecimal string object id of 12 byte in method parameter, lets take an example:

There are some methods of ObjectId, below are the details :

  • str : provides string representation of object id.
  • valueOf() : returns the hexadecimal representation of ObjectId.
  • getTimeStamp() : returns the creation timestamp of objected.
  • toString() : returns the string representation of ObjectId in the “ObjectId(haxstring)”

Back to top

Explain GridFS in MongoDB? Give a practical example with source code for adding files to GridFS.

Let say we need to store large data files in MongoDb, how to do that, in a single document ? No, since MongoDb has limitation for a document to have maximum size of 16MB. Now how about storing data which has size more than 16 GB. In such scenarios GRIDFS comes to rescue us. GridFs is a MongoDb specification that enables us to store data that has size more than 16MB.  These large files can be some audio files or large images or might be a video file. In a way it is a kind of file system storage but still the data is store in MongoDb collections.

GridFS divides a large record ie a file into small chunks and it stores these chunks of data in documents, and each document has the maximum size of 255 kb.

GridFs uses two collections to store the large data, one collection is used to store the file chunks and other one is to store its metadata. These two collections are known as fs.files and fs.chunks to store file metadata and chunks.

When we want to retrieve the large dataset from MongoDb server, the MongoDb drivers reassembles the data from chunks and returns the data to calling function.

Syntax to store file using GridFs is:

To find the document in the database, find() method is used, below is the syntax for the same:

Lets take an example to store a large file in mongo db server :

To store a file we need to traverse through the bin directory of mongodb installation:

Lets suppose we need to store the below file that is around 52MB in size. GridFS in MongoDBLets try to store this file using GridFS.Files using GridFS

As we can see the BookStoreDB has now the video file that is of 52 mb, and the file has been stored.

Lets try to find the file that we have just stored:Video File in MongoDB

As we can see in the output, we just got the file data from GridFs that we have stored.

To get all the chunks present, we can use the following command:MongoDB Commands

Running this file will return all the chunks. Notice we have used the files_id, as we got in the find command with chunks.

Back to top

How database relationship(1:1,1:N,N:1) is maintained in MongoDB? Explain with proper example.

Like relational database where records are relationally referenced in different tables maintaining the relationship as one to one (1:1), one to N (1:N), N to one (N:1), N to N (N:N). Relationship in MongoDB represents the way documents are logically connected to each other. In MongoDb these relationships are modeled in two ways :

  • Embedded
  • Referenced

Lets take an example of our BookStore application, where user can take one to N books on rent. Here in our database this relationship will be relationship will be in One to N (1:N).

Lets try to achieve this using the Embedded approach:MongoDB Inserts

As we can see in the example above we have inserted record with embedded approach, Here Alax user has two books Head First Java and Head First Design Patterns. In the embedded approach a single documents have the embedded records referenced. This approach have all the related data in the single document and if we need to find the whole document below will be the query to find one:MongoDB Find Command

As we can see from the query above, it resulted us the whole document that we have inserted.

So in essence in the embedded approach, we have all the related documents/records in a single document.

Now let’s move to another approach that is Reference approach :

In this approach instead of having all document in a single document, we will have separate document and these are referenced with ObjectId.MongoDB Reference with ObjectId

As we can see in the example above, the object ids are just dummy ids for demo purpose. In the next section we will be taking an example wherein we will insert two separate book records and we will be referencing these documents through their ObjectIds.

Lets try to store the Book documents and try to find to get the object id with which we will be referencing:Store Document in MongoDB

In the example above we have inserted two records for two books, Head First Java and Head First Design Pattern. And in the next step we have tried to find the records and we can see the inserted records in the BookStoreDB.

Now lets try to reference the documents to a user with reference approach:Referenced Way in MongoDB

This way we can store the records in referenced way in MongoDB.

Back to top

What are atomic operations? How automicity is achived in MongoDB, explain with example.

Atomicity is an important aspect of database that comes under ACID concept. NoSql databases have some difference with respect to handle atomicity as compared to traditional relational database systems and so as MongoDB. Lets try to understand what automicity is : Automicity is a concept where in while updating some records in the database either all records should update in a transaction or no record should update. Basically we can refer it to an atomic transaction.  What automicity garuntees is either all records of database will update in a transaction or no record will update, that prevents the partial updation.

MongoDb also supports automicity but as we discussed in some different manner. In MongoDB there is a constraint that only one document can be updated as part of a single transaction. There can be multiple documents in a single document and it can be updated keeping automicity, but if there will be multiple documents then automicity cannot be achieved in MongoDb, so in essence we can achieve automicity in MongoDb but on a single document.

So what if we still we want to achieve automicity on multiple documents, here you need to use two phase commit to achieve the same. But the recommended approach to achieve automicity is to have the embedded documents, ie. To have all the related documents in one place.

Lets try to understand the same with help of an example:

Lets suppose we have a book store and in our bookstore we are maintaining the total number of “Head First Java” books and the remaining number of books, also at the same time we are maintaining the record about the user who bought the book. So a buy operation from frontend, and the below actions will performed at backend :

  • Decrese the available number of books by 1.
  • Update the Buyer Information with the user details who bought this book.

Below is how the document looks like for the same:

So as we can see we have embedded the Buyer Information document with this in order to achieve atomicity. Whenever a buy book request will made from front end, at database side first it will check for the available number of books, if the available number of books is greater than 0, then the available books count will be decreased by one and the buyer information will be updated in the embedded document, Buyer Information that is embedded with the main document.

To update a document in MongoDb we will use findAndModify() method. Let’s take an example with the scenario above how we can use the findAndModify() method:

The above code fragment first checks that if the available books are greater then zero, if the count is greater than zero than in the update part first decrease the count of available books by 1 and add the buyer information in the Buyer Information embedded document.

Back to top

Explain MapReduce in MongoDb with example?

MapReduce is a concept of processing large set of data and return an aggregated result.

From MongoDb official site :
“Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. For map-reduce operations, MongoDB provides the mapReduce database command.”

MapReduce is usually used where we need to process large datasets.

Lets go through the map reduce command in MongoDb:

Lets go through each term used in command one by one :

map, maps value with key and emits a key,value pair.

reduce, reduces the key value pair and group all the values with same keys.

out, indicates the location to put the result.

query, indicates if there is any thing that needs to be selected based on some criteria.

sort, Boolean field, indicates that the result needs to be sorted or not.

limit, is the number of documents that needs to be returned.

Let’s now try to understand the same with help of an example. Consider a scenario where have a online portal and we are getting a kind of items from different companies. Typically our document structure is like:

Using this type of recordsets we will use map reduce to do some stuff. Lets first insert some records in our online portal database.MapReduce in MongoDB

So our onlineportal database is ready and we have populated some records for MobilePhone category. Now Lets play with map reduce features :

Suppose we want to count the number the items from each company, below is how we will write command for the same using MapReduce:MongoDB MapReduce Commands

As we can see, we wrote a command used company in map and used the key in reduce function, with a counter. In results section we got the expected result that Company Apple have 5 products/items in our db, Samsung has 4 and sony has 4.

Now in another requirement we want to count the number of MobilePhones that have Price greater then 40000, lets see how we can achieve this :

We will use query in this case and we will try to find out the records that have price greater then 40000. Below is the example:Query MongoDB

As we can see, we have the results now and in the way we wanted, Apple has 2 phones that have Price greater then 40000, Samsung has 1 and Sony has 3. If you give a close look at the command that we have used here from the last example we have just added a new thing here that is query,  and added the condition what we required and map reduce gave us the results in a flash.

This way we can process a very large dataset in our application using MapReduce.

Back to top

What is capped collection in MongoDb? How capped collections are created in MongoDb?

Capped collection is a special kind of collection in MongoDb, what can have limit on collection storage. That means in this collection we can restrict the size of collection or we can put limit on size of collection, these special type of collection is named as Capped Collection.

Lets take a look at the syntax of creating capped collection:

The syntax is near about same as the syntax of creating collection. Lets understand the syntax first :

Collection_Name : Name of collection that needs to be created as capped collection.

capped : Capped is the Boolean flag, true if the collection needs to created as capped collection, by default the value is false.

autoIndexId : Boolean flag, used for autoindexing, if true indexes will be created automatically, false will say indexes will not be created automatically.

size : Size parameter says the max size of documents in bytes, it is mandatory field in case of capped collections.

max : max parameter says the max number of documents allowed in a collection. Size is given preference over size.

MongoDb provides a method isCappped() to check if the collection is capped or not. Below is the syntax for the same:

Back to top

Give a practical example of creating Capped Collection in MongoDB?

Let’s try to create a capped collection and try to simulate with some number of documents:

Consider a scenario wherein we have a bookstore application and we are logging the user data, and we want this data shouldn’t go over 3 documents. So we will be creating a capped collection that will have of capped collection type and have the restriction of keeping 3 documents, just to simulate this our example will not have the actual log data but just the documents having dummy data.

Lets first start with creating a capped collection in our BookStoreDB:

Capped Collections in MongoDB

Here we have created a collection named Logs as capped collection and provided the max document as 3 and max size as 200Bytes. In next command we have checked with the method isCapped() that if the collection is capped or not.

Let’s try to insert data in our collection:Insert Data in MongoDB Collection

So till now we have created a capped collection with max size of 3 documents, we have inserted three documents and the same reflected in the find command. Now since the collection is size of 3 documents and its now reached its threshold, now if we add another document, the oldest one will be overridden by newer one.

Let’s create a new record and try to find the documents in the collection:

Find Document in MongoDB Collection

So we have inserted a new document, lets try to list the documents now:

Insert new document in MongoDB

So as we can see the old document of user John is overridden now, since the Logs collection is capped collection and of the max size of 3 documents.

Capped collections are useful for log files, these collections only allow updates on original document size which ensures that the document will not change its location on disk. The same is also a disadvantage as well since if the update go beyond the size then the update will fail. One more disadvantage is that we cannot delete a document from capped collection.

Back to top

Does MongoDb support regular expressions? If yes, explain searching in MongoDb with regular expression. Implement an example.

Regular expressions are used in software applications among various languages to find pattern from a string or from a document or from database. MongoDb also have support for regular expressions. In relational database systems we use like and % for pattern matching in string. In MongoDb as well the same can be achieved using pattern matching as well as using regular expressions.

Lets understand the same with example:

To start with this we will add some data in a collection. In our BookStoreDB, we are going to add some books with name, author and isbn number.Add Books to MongoDB

So in our allbooks collection, we have inserted some records for books. Now lets try to search in our collection using regex :

Syntex to search some string in document from json is:

Lets understand the syntax :

Collection_Name is the name of collection under which we need to perform searching.

FieldName is the name of key, whose value needs to be find with regex.

$regex is the regular expression syntax in MongoDB.

Pattern is the pattern which needs to be search.

Lets apply the syntax and try to search from the allbooks collection, where we need to find the book name which have “Java”.Regular Expressions in MongoDB

As we can see we got the results that have value as Java.

Now there might be scenario where we need to search for exact string, let suppose we have one more book that has name as “JavaScript In Web”, and if we will try to apply our search we will get the same in result as well, since JavaScript have the Java word in it. To avoid such scenarios there are some special characters available in MongoDb that comes in action to rescue, there are $ and ^.

^ (Caret) used to make sure that the string should start with the character given in pattern whereas $ used to make sure that the string should end the character given in the pattern.

If we want to make our search case insensitive then we need to use $options with our search.Regex in MongoDB

If we don’t want to use regex for pattern matching, then there is another option available that is to use /<pattern>/ in find command, below is the syntax for the same: Regex Patterns in MongoDBThis is all about pattern matching using regex in MongoDb.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

NodeJS Course
Take this Course Online Now

Hopefully, this series of MongoDB Interview Questions with detailed answers including source code will be an ultimate source for Interview preparation. Next we are going to cover more MEAN Stack related topic, so keep in touch :)

Top Technical Interview Questions and Answers Series:

Top 20 Backbone.js Interview Questions

Today, we are going to cover another topic in Technical Interview Questions and Answers Series i.e. Backbone.js. Previously, we explored various JavaScript Libraries and Frameworks including jQuery, AnguarJS 1.x & AngularJS 2, ReactJS, NodeJS etc. We tried to cover the maximum areas in each Technology so that reader at each level (Beginner or Intermediate or Advanced one) can take advantage from it.Backbone JS Interview Questions

BackboneJS is another famous JavaScript Library, we will explore all various features by following Interview Question and Answer pattern as we did earlier.

Backbone.js Interview Questions PDF version will be available later for download.

Backbone.js Interview Questions List

What is Backbonejs? What are the key advantages of using Backbone.js? Is there any downside using BackboneJS?

What is Backbone.js?

Backbone.js is mainly a light weight JavaScript library rather than a framework which is used to structure code in a large scale application or a single page web application. The other features of backboneJS are as follows:

  • It follows Model-View- Controller (MVC) architecture.
  • It provides functionality to access database and manipulate data.

What are the key advantages of using BackboneJS?

  • It provides minimal set of data structure only Model and Collection to develop applications ranges from embedded widget to large scale.
  • Views and URL are user interface which are capable of binding to model and event.
  • There is no performance drawback of using backboneJS in large scale application.
  • It provides dynamic Model – View and Model – Event binding.
  • The main feature of backbone.js is that it provides a way to manage and organize code.

Downside using Backbone.js?

It is not a complete framework, therefore in the era of ReactJS and AngularJS the usages of BackboneJS is very few and its getting to be obsolete day by day.
Back to top

How Backbone different from other JavaScript Frameworks like AngularJS, ReactJs etc.

Framework Engine:

Backbone.js does not provide framework engine, on the other hand, emberjs, angularjs and reactjs provide their own framework engine.

Template Engine:

Angular, Ember and React provides their template engine for development, however backbone allow user to choose independently.

However, backbone.js is light, easy to learn and easily adoptable.

BackboneJS Vs AngularJS Vs ReactJS Vs Ember?

According to the google trend, backbonejs gained some popularity around 2012. However, after 2014, backbone.js has lost its popularity to reactjs and angularjs.Backbone Vs Angular Vs React

Back to top

How to set up environment for BackboneJS? Explain by following a step by step approach.

  • Create a new folder with the name same as project name.Backbonejs Project
  • Create a file called index.html. This is the main html  file for the app.Backbonejs Libraries
  • Now organize folders for different components inside the folder called ‘components’. For each components there will be a folder for models, a folder for collections and a folder for views and html templates. For example, here is the folders and files for ‘book’ component.Components in Backbonejs
  • Create a folder for routers called ‘routers’.
  • Create folder for assets.
  • Finally, the folder structure for the project will look as following:Backbonejs Example App
  • On index.html.
     

Back to top

What are the main components of Backbone.js? Discuss in detail the architectural style of BackboneJS Application with the help of a diagram.

What are the main components of Backbone.js?

The main components of backbone.js are as following:

  • Events
  • Backbone.Model
  • Backbone.Collection
  • Backbone.Router
  • Backbone.Sync
  • Backbone.View

Backbone.js Application Architecture

Events:

Events are the core component of backbonejs. This is the basic way of controller. Events is accessible by an instance of Model, Collection, View, Router and History. Therefore, any instance of Model, Collection, View, Router and History can dispatch and listen to event to which they are bind to.  The global ‘Backbone’ can also access events as following:

The second parameter which is a function is registered as a handler to be called when a specific event by the name passed as the first parameter occurs. Similarly, for any instance of any model can access Event.

For example, if an object called Obj1 wants to notify another object whenever it gets changed, it can dispatch the notify event. Any object interest to listen to the change of Obj1 can bind to the ‘notify’ event and can listen to when Obj1 gets changed and can perform necessary action they require. Obj1 does not need to know who is listening to it’s notify event and what they are performing on it’s change.

There are some core events such on, off, listento and trigger.

Backbone.Model:

In a MVC framework like backbone.js, Model is the main fundamental concept. A model is a representation of any component use in application. Therefore, a model can be represented as following:BackboneJS Model

Each Model in Backbone js are created by extending Backbone.Model.

Here default is used if we want to set any default attribute to every instance of the Model.

Now if we create an instance of Book Model as following:

Every time a new instance of a Model will be created, the initialized will be called. On the console, the output would be:Backbone Model Output

Backbone.Model provides getter and setter in order to access the Object directly. If we want to access the title attribute of Book Model for any of its instance we just need to access as book1.get(…). Similarly,  Backbone.Model provides setter to change any of it’s attribute.

The output of getter and setter would be as following:Model getter and setter

It is possible to use  on event to detect change in any of the instance for example,

The output would be:Backbone Model Getter Output

Backbone also supports model validation through model.validate() . For example:

Here , the validate method of the Book model defines the required attribute of Book object and define the corresponding error message. Now by using {validate: true} while creating an instance of the Model. For example:

Here is the output, as description attribute for the instance book1 has not been given.Backbone Description Attribute

Backbone.Collection:

The next component for backbone.js is collection. Collection is usually a list of instance of a particular Model which is created by extending Backbone.Collection. Every collection is bind to a Model. Here is an example of a collection of Objects of type Book Model.

Now if we create an instance of the collection as following:

The output would be as following:Backbone Collections

Backbone.Router:

Routers are created by extending Backbone.Router which gives the way to communicate between different action, events and view. This is just like a default navigation for Backbone.js application. Router are triggered or started by Backbone.History. Usually it is recommended to have a single router parent for an application.  Router.navigate() is another function of Router class which is triggered in order to change the the route along with updating the URL by passing the trigger:true option.

Backbone.Router can also be bound to event as like Model, Collection and View. On triggering “route” event on the router, it is possible to control the navigation as following:

Backbone.Sync:

Every time there is a read, save, or delete models operation, Backbone.sync is called. It makes RESTful requests using jQuery. This can be overridden.

Backbone.View?

Backbone View is used to represent any Model or collection on the DOM of HTML. Therefore, View is usually a HTML element which is added to the DOM of the Html Page. If there is any user action such as keyup, keydown, corresponding view of the element get notified. If there is any change in the model that is being represented by the View, the view get notified and can take necessary action defined.  Backbone.View class is also kind of a controller, dispatch events and change the DOM element accordingly.

Back to top

 What is Backbone JS Event? Explain event handling in backbone.js with an example.

BackboneJS Events can be bound to view, model and collection. Therefore, it is possible every time there is a change in any of these three main components of BackboneJs, corresponding event triggered.

Therefore, every view can be connected to particular event.  According to the above example, every time there is a key up event occur on the input html element with id ‘input-text’, the corresponding method ‘change’ will be triggered.

Similarly, event can be bounded to Collection, Model and View element as well.

Back to top

How to Read files (JSON) in BackboneJS.

Backbone.Collection can be defined using JSON File. For example, if we have a JSON file called books.json with a number of instance of Model Book.

And Now if we want to create Collection instance using the JSON file. We can use fetch method of Backbone.Collection.

The output would be as following:JSON in Backbone

Back to top

How to implement HTTP Requests, for example GET, POST, PUT and DELETE using Backbonejs? Explain With example?

BackboneJS does not provide own framework, therefore, it requires separate framework for making HTTP request.  Therefore, it requires third party library for example Express.js and Node.js.

  • Install NodeJS.
  • Inside the project folder, create a package.json file.
  • Install libraries using ‘npm install command’.
  • Create a server.js file.
  • Run the script ‘node server’.

Back to top

Explain History and its usage with example?

Backbone.History is used to keep track of the navigation history of different routes, it is also used to match the appropriate route, fires callbacks to handle events. Therefore, Backbone.History enables routing in application.

The first requirement of enabling routing in the application is to create a router extending Backbone.Router. The next step is to create an instance of the router, for example:

  • This start method of Backbone.History starts listening to routes and manages the history.
  • It monitors the trigger of ‘hashchanged’ which is trigger every time the route is changed. This method can be called once.
  • Any subsequent calls to Backbone.history.start() will throw an error, and it will return the Backbone.History.started variable which is a boolean value indicating the status of History monitoring either started or not.
  • Backbone.history.start([options]), this can receive a parameter options. For modern browser, this options can be  {pushState: true} and for old browser, that does not support pushState, this can be ‘{hashChange: false}’.
  • Backbone.history.start() returns true. If no defined route matches the current URL, it returns false.
  • It is recommended to call start() only after the DOM is ready.

Another method of Backbone.History is navigate. For example, once a model has been saved if we want to redirect the navigation to the index page, it could be done as following:

Back to top

How to use child views? Explain with example.

  • In index.html page create a container for the IndexView.
  • Create a new view called BookIndexView.
    This View has a method called ‘addChildView’ which will be used to add child View in the parent View.
  • The html template for BookIndex view is as following:
  • Now Lets create the child View for each Book. Where each book View would look like:ChildView in BackboneJS
  • The Html template for BookView book.html.
  • The Javascript for BookView.
  • In index.html include book.js book_index.js.
  • Now if we render BookIndexView as following:
    The output Would be:BackboneJS List Child View
  • Now if we add a child View as following:
    Output would be:List ChildView Backbone Tutorial
    If we add one more it would look like:
    Output would be as following:BackboneJS ChildView Tutorial

Back to top

What is Collection in Backbone.js? Explain with example.

Collections are set of Model created by extending Backbone.Collection. Collections are used to represent an array of object.

To create a collections in Backbone.js application, it is required to create an object of type model. This object need at least one property which is required. The new collections would be a set of this created model.

For example:

Output:Backbone Collection Tutorial

Event Handling in Collections:

It is possible to declare event in order to change the collections.