Mern Stack
Mern Stack
MONGODB
1.What is MongoDB?
Answer: MongoDB is a NoSQL database that provides high performance, high availability, and
easy scalability. It stores data in JSON-like documents, making it easier to work with for
developers.
Answer: Unlike traditional RDBMS that use tables and rows, MongoDB uses collections and
documents. It doesn't enforce a schema, making it more flexible to handle unstructured data.
Answer: A replica set in MongoDB is a group of MongoDB instances that maintain the same data
set. Replica sets provide redundancy and high availability.
Answer: Sharding is a method for distributing data across multiple servers in MongoDB, allowing
the database to handle large datasets and high throughput operations.
Answer: MongoDB provides aggregation operations to process data and return computed
results. These include $match, $group, $project, $sort
Answer:You can perform a query in MongoDB using the `find()` method. For example,
`db.collection.find({key: value})` will return all documents matching the specified key-value pair.
11. How do you insert data in MongoDB?
Answer: You can insert data in MongoDB using the `insertOne()` or `insertMany()` methods. Example:
`db.collection.insertOne({name: "Alice", age: 25})`.
Answer: An index in MongoDB is a data structure that improves the speed of data retrieval operations.
Answer: The Aggregation Framework in MongoDB is a powerful tool for data aggregation and
transformation, allowing you to perform operations like filtering, grouping, and sorting.
Answer: MongoDB Atlas is a fully managed cloud database service provided by MongoDB. It automates
complex database tasks such as setup, backups, and scaling.
-Answer: MongoDB supports multi-document transactions that provide ACID guarantees. You can use
`startTransaction()` and `commitTransaction()` to manage transactions.
Answer: However, you can define and enforce a schema using Mongoose in Node.js or JSON Schema.
Answer: MongoDB achieves horizontal scalability through sharding, distributing data across multiple
servers to handle more traffic and larger datasets.
Answer: In MongoDB, the `_id` field serves as the primary key for a document. It is automatically created
by MongoDB if not provided.
Answer: GridFS is a specification for storing and retrieving large files in MongoDB. It divides files into
chunks and stores each chunk as a separate document.
-Answer: MongoDB uses a locking mechanism at the database level for concurrency control, ensuring
that only one operation can modify the data at a time.
Answer: Write Concerns in MongoDB define the level of ac`knowledgment required from MongoDB
when performing write operations.
Answer: The `findOne()` method returns the first document that matches the query criteria. Example:
`db.collection.findOne({name: "Alice"})`.
Answer: The Aggregation Pipeline is a framework for data aggregation in MongoDB, consisting of
multiple stages that transform and process data sequentially.
Answer: MongoDB supports text search through text indexes. You can use the `$text` operator to
perform a text search on a collection.
- Answer: A Covered Query is a query in which all the fields in the query are part of an index.
Answer:Use the `sort()` method to sort the results of a query. Example: `db.collection.find().sort({name:
1})` will sort the documents by name in ascending order.
Answer: A capped collection is a fixed-size collection that automatically overwrites its oldest entries
when it reaches its maximum size.
-Answer:MongoDB replicates data through replica sets, where one node is the primary node that accepts
write operations, and the other nodes are secondary nodes that replicate the data from the primary.
33. What is the $match operator in MongoDB?
Answer: The `$match` operator filters documents in the aggregation pipeline based on the given criteria,
similar to the `find()` method in regular queries.
Answer:Projection operators in MongoDB allow you to specify which fields to include or exclude in the
result set of a query.
Answer: The `$lookup` operation in MongoDB is used to perform a left outer join to other collections,
allowing for combining related data from multiple collections.
Answer: MongoDB can create indexes on embedded documents using dot notation. Example:
`db.collection.createIndex({"address.city": 1})`.
Answer: MongoDB supports various data types, including String, Integer, Boolean, Double, Array, Object,
Date, Null, and ObjectId.
Answer: MongoDB can match documents that contain the null value .
Answer: The `$unwind` stage in the Aggregation Framework deconstructs an array field from the input
documents to output a document for each element in the array.
Answer: You can use `mongodump` to back up data and `mongorestore` to restore it.
Answer: A MongoDB Atlas Cluster is a group of databases hosted in the cloud that can be scaled up or
down based on demand.
Answer: The `$elemMatch` operator is used to match documents that contain an array field with at least
one element that matches all the specified criteria.
44. What is a cursor in MongoDB?
-Answer: A cursor is an object in MongoDB that points to the result set of a query.
- **Answer:** The `$inc` operator is used to increment the value of a field by a specified amount.
Example: `db.collection.updateOne({_id: 1}, {$inc: {count: 1}})`.
Answer:You can use `mongoexport` to export data from MongoDB to a CSV, JSON, or TSV file.
- **Answer:** The `$set` operator is used to update the value of a field in a document. If the field does
not exist, it creates the field.
2.Express js-
1. What is Express.js?
Answer: Express.js is a fast, web framework for Node.js, designed to build web applications and
APIs.
Answer: It simplifies server-side code, handles routing, middleware, and integrates well with
databases and templates.
Answer: Middleware functions are functions that have access to the request object, response
object, and the next middleware function in the application’s request-response cycle.
Answer: Use app.get(), app.post(), app.put(), app.delete(), etc., to handle different HTTP
methods.
Answer: Routes are the endpoints that define how an application responds to a client request to
a particular URI.
7. What is the role of next() in Express.js?
Answer: next() is a function in Express that passes control to the next middleware or route
handler.
Answer: Define an error-handling middleware function, which takes four arguments: err, req,
res, and next.
Answer: app.use() applies middleware globally to all routes, while app.get() handles specific GET
requests.
Answer: These middleware functions parse incoming JSON payloads and URL-encoded data,
respectively.
Answer: Define routes using app.get(), app.post(), etc., or use express.Router() to create
modular routes.
Answer: RESTful API is an API that adheres to the REST architecture, utilizing HTTP methods like
GET, POST, PUT, DELETE.
Answer: Define routes corresponding to each RESTful operation (GET, POST, PUT, DELETE) in your
Express app.
Answer: Express.js generators create a boilerplate for applications, providing a starting point
with basic configurations.
Answer: Use middleware like multer to handle multipart/form-data for file uploads.
Answer: Organize the code into routes, controllers, models, and middlewares directories for
better maintainability.
18. How do you use template engines in Express.js?
Answer: Set the view engine (e.g., Pug, EJS) using app.set('view engine', 'pug') and render views
with res.render().
Answer: req.params contains route parameters, which are part of the URL, e.g., /user/:id.
Answer: req.query contains query string parameters in the URL, e.g., /search?q=term.
Answer: req.body contains data sent by the client in the body of a POST or PUT request.
Answer: Use helmet middleware, validate input data, handle errors correctly, and use HTTPS.
Answer: Use cookie-parser middleware to parse and manage cookies in your application.
Answer: Add a middleware at the end of the route definitions to handle unmatched routes, and
return a 404 status.
Answer: res.send() sends a response of any type, while res.json() specifically sends a JSON
response.
32. What are app settings in Express.js?
Answer: App settings are properties on the Express application object that control application
behavior, e.g., app.set('view engine', 'pug');.
Answer: Use environment variables and the process.env object to manage configurations like
port numbers, database connections, etc.
36. What are the common HTTP status codes used in Express.js?
Answer: Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), 401
(Unauthorized), 404 (Not Found), 500 (Internal Server Error).
Answer: res.render() renders a view template and sends the rendered HTML to the client.
Answer: A session stores user data on the server. Use express-session to manage sessions in
Express.js.
Answer: app.locals is an object that contains local variables available throughout the application.
Answer: app.listen() is a shorthand for creating an HTTP server and binding it to a port, while
server.listen() provides more control over the server creation.
Answer: morgan is a logging middleware that logs HTTP requests and responses.
Answer: Catch errors using try-catch blocks, handle them in middleware, and return meaningful
error messages.
Answer: Send a response using methods like res.send(), res.json(), or res.end(). The cycle is
terminated once a response is sent.
Answer: app.route() is used to create chainable route handlers for a particular path.
React js-
1. What is React?
Answer: React is a JavaScript library developed by Facebook for building user interfaces,
especially single-page applications where data changes over time.
Answer: The key features include Virtual DOM, Components, Unidirectional Data Flow, and
Lifecycle Methods.
3. What is JSX?
Answer: JSX is a syntax extension for JavaScript that looks similar to HTML or XML. It is used with
React to describe what the UI should look like.
Answer: The Virtual DOM is an in-memory representation of the real DOM elements generated
by React components before any changes are made
Answer: There are two main types of components: Functional Components and Class
Components.
Answer: Props (short for "properties") are read-only attributes passed from parent components
to child components. They are used to pass data and event handlers to child components.
Answer: State is an object that holds data that may change over the lifecycle of a component.
Answer: Props are immutable and passed to components, while state is mutable and managed
within the component. Props are external, and state is internal to the component.
Answer: Lifecycle methods are special methods that get called at different stages of a
component's life. Common lifecycle methods include componentDidMount,
componentDidUpdate, and componentWillUnmount.
Answer: The render method is required in class components and is responsible for returning the
JSX that makes up the component’s UI.
Answer: Hooks are functions that let you use state and other React features in functional
components. Examples include useState, useEffect, and useContext.
Answer: useState is a Hook that allows you to add state to functional components.
Answer: useEffect is a Hook that lets you perform side effects in function components, such as
fetching data or directly interacting with the DOM.
Answer: Redux is a predictable state container for JavaScript apps, often used with React for
managing the app’s state in a more structured way.
Answer: The three core principles are: Single Source of Truth (one store), State is Read-Only, and
Changes are made with Pure Functions (reducers).
Answer: A pure function is a function that, given the same inputs, always returns the same
output and does not have any side effects (like modifying a global object).
Answer: Actions are plain JavaScript objects that have a type property and describe an intention
to change the state.
Answer: Reducers are pure functions that take the current state and an action as arguments and
return a new state.
Answer: Redux Thunk is a middleware that allows you to write action creators that return a
function instead of an action. This is used for handling asynchronous logic in Redux.
25. What is the difference between Redux and the Context API?
Answer: Redux provides a more robust way to manage global state with a central store,
middleware, and strict rules, suitable for smaller applications.
Answer: Forms in React are handled using controlled components where form data is managed
in the component's state, or using uncontrolled components where data is handled by the DOM.
Answer: The key prop is a special attribute you need to include when creating lists of elements.
It helps React identify which items have changed, are added, or are removed, improving
performance.
Answer: You can optimize a React application by using memoization (e.g., React.memo),
avoiding unnecessary renders, code splitting.
29. What is lazy loading in React?
Answer: Lazy loading is a technique that delays loading of components until they are needed.
React supports this with React.lazy() and Suspense.
Answer: React Router is a standard library for routing in React. It enables navigation among
different components in a React application, allowing for dynamic client-side routing.
Answer: Routing in React is handled using the React Router library, where you define routes
using <Route> components inside a <Router>.
Answer: HOCs are functions that take a component and return a new component.
Answer: PropTypes is a type-checking feature used to ensure that the props passed to a
component are of the correct type and structure.
Answer: The ref attribute provides a way to access the DOM nodes
Answer: Error boundaries are components that catch JavaScript errors in their child component
tree, log those errors, and display a fallback UI.
Answer: React.Fragment is a component that lets you group multiple elements without adding
extra nodes to the DOM.
Answer: Reconciliation is the process by which React updates the DOM with the results of
rendering a component.
Answer: Data can be passed between components via props for parent to child communication,
and through callback functions or Context API for child to parent or sibling communication.
Answer: React Portals provide a way to render children into a DOM node that exists outside the
hierarchy of the parent component.
Answer: Synthetic events are React's cross-browser wrapper around the browser's native events,
providing a consistent API.
Answer: Redux-Saga is a library that manages side effects in a Redux application using generator
functions, making it easier to handle complex asynchronous flows.
Answer: SSR is the process of rendering React components on the server and sending fully
rendered pages to the client.
Answer: Hydration is the process of attaching React's event listeners to the HTML content that
has been rendered by React on the server.
Answer: useEffect runs asynchronously after the render is painted on the screen, while
useLayoutEffect runs synchronously before the painting, which can block visual updates.
4.Node js-
1. What is Node.js?
Answer: Node.js is a runtime environment that allows you to run JavaScript on the server side.
2. How does Node.js handle asynchronous operations?
Answer: Node.js uses an event-driven, non-blocking I/O model, where callbacks are used to
handle asynchronous operations.
Answer: npm (Node Package Manager) is used to manage Node.js packages, including installing,
updating, and removing them.
Answer: A callback is a function passed into another function as an argument, which is executed
after the completion of the asynchronous operation.
Answer: The Event Loop is a core part of Node.js that handles all asynchronous callbacks. It
allows Node.js to perform non-blocking I/O operations.
Answer: Streams are objects that let you read data from a source or write data to a destination
continuously. They are used for handling I/O operations efficiently.
Answer: process.nextTick() is used to defer the execution of a callback function until the next
iteration of the Event Loop, while setImmediate() schedules the callback to be executed on the
next iteration of the Event Loop.
Answer: Node.js provides the fs module to perform file operations like reading, writing,
updating, and deleting files.
Answer: Middleware functions are functions that have access to the request object (req), the
response object (res), and the next middleware function in the application’s request-response
cycle.
12. What is Express.js?
Answer: Express.js is a minimal and flexible Node.js web application framework that provides a
robust set of features to build web and mobile applications.
Answer: Errors in Node.js can be handled using try-catch blocks, the error-first callback pattern,
and error events.
Answer: A promise is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value.
Answer: Modules in Node.js are blocks of encapsulated code that communicate with an external
application based on their functionality.
Answer: A module is created by writing a JavaScript file and exporting objects, functions, or
variables using module.exports.
Answer: require is used to load modules in Node.js (CommonJS modules), while import is used
in ES6 module.
Answer: Packages in Node.js are managed using npm or yarn for installing, updating, and
removing packages.
Answer: eventEmitter is a class in Node.js that facilitates communication between objects via
events. It can emit named events and handle them via listeners.
Answer: HTTP requests are handled using the http or https modules in Node.js, or using a
framework like Express.js.
Answer: Buffer is a global object in Node.js used to handle binary data directly in the form of a
buffer array.
Answer: readFile reads the entire file into memory, whereas createReadStream reads the file in
chunks, making it more efficient for large files.
23. What is cluster module in Node.js?
Answer: The cluster module allows you to create child processes that share the same server
port, enabling load balancing in Node.js applications.
Answer: REPL stands for Read-Eval-Print Loop, an interactive shell that processes Node.js
expressions.
Answer: Improving performance can be done by using clustering, caching, optimizing query
performance, and minimizing the use of synchronous functions.
Answer: Node.js is single-threaded with an event loop, but it can handle multi-threading using
the worker_threads module for running JavaScript code in parallel threads.
Answer: The path module provides utilities for working with file and directory paths.
Answer: Middleware in Express.js is a function that can access the request and response objects
and can either end the response or pass control to the next middleware function.
Answer: Routing in Node.js can be handled using Express.js by defining routes that respond to
specific HTTP methods and URLs.
Answer: CORS (Cross-Origin Resource Sharing) is a security feature that restricts resources on a
web page to be requested from another domain. It can be handled using the cors middleware in
Express.js.
Answer: The os module provides operating system-related utility methods and properties.
Answer: npm init is a command used to create a package.json file for your Node.js project.
Answer: Both are package managers for Node.js, but Yarn is known for faster performance and
better dependency management.
Answer: Some global objects in Node.js are __dirname, __filename, process, Buffer, and global.
Answer: The dns module provides functionalities to perform DNS lookups and name resolution
functions.
Answer: Some ES6 features used in Node.js include arrow functions, template literals,
destructuring, let and const, and promises.
Answer: console.log outputs messages to the standard output (stdout), while console.error
outputs messages to the standard error (stderr).
Answer: Debugging can be done using the Node.js inspector, console.log statements, or IDE
debugging tools.
Answer: Middleware chaining is when multiple middleware functions are executed sequentially
in a chain, where each middleware passes control to the next one.
Answer: req.params is an object containing properties mapped to the route parameters, often
used for dynamic route matching.
46. What are cookies and how do you handle them in Node.js?
Answer: Cookies are small pieces of data stored on the client side. They can be handled using
the cookie-parser middleware in Express.js.
Answer: req.query is an object that contains the query string parameters of a request.
Answer: Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js,
providing a schema-based solution to model your application data.
Answer: The child_process module allows you to spawn child processes, enabling you to execute
shell commands and scripts.
5.Bootstrap
1. What is Bootstrap?
Answer: Bootstrap is a free, open-source front-end framework used for developing responsive
and mobile-first websites. It includes HTML, CSS, and JavaScript components.
Answer: Some advantages include responsive design, pre-built components, consistent design
by using reusable code, ease of use, and community support.
Answer: Responsive design ensures that the layout and components of a website adjust
dynamically based on the screen size and orientation of the device.
Answer: A container is a wrapper for Bootstrap content. It helps to center the content
horizontally and provides responsive behavior.
Answer: There are two types of containers: .container (fixed-width) and .container-fluid (full-
width, spanning the entire width of the viewport).
6. What is the Bootstrap Grid System?
Answer: The Bootstrap Grid System is a flexible system for creating layouts. It uses a 12-column
layout system to align content.
Answer: The grid system divides the page into 12 columns. You can combine columns to create
custom widths using classes like .col-, .col-sm-, .col-md-, .col-lg-, and .col-xl-.
Answer: Breakpoints are the points at which the website layout will adjust according to the
screen size. They are predefined by Bootstrap for different screen sizes: Extra small (XS), Small
(SM), Medium (MD), Large (LG), and Extra large (XL).
Answer: Bootstrap components are pre-designed elements such as buttons, forms, navbars,
modals, and more, which can be easily integrated into a website.
Answer: Bootstrap can be included by using a CDN link or by downloading and including the
Bootstrap CSS and JS files locally.
Answer: A Navbar is a navigation header that can include branding, navigation links, forms, and
other elements, and can be toggled for small screens.
Answer: Use the .navbar, .navbar-expand-*, and .navbar-toggler classes to create a responsive
Navbar that collapses on smaller screens.
Answer: The .navbar-brand class is used for the branding logo or text within the Navbar.
Answer: A Jumbotron is a lightweight, flexible component for showcasing hero unit style
content.
Answer: A card is a flexible and extensible content container with multiple variants and options,
including headers, footers, images, and more.
17. What are Bootstrap Forms?
Answer: Bootstrap Forms are pre-styled form controls that make creating forms easier and
ensure consistent design across the website.
Answer: The .form-group class is used to wrap form controls and labels to ensure proper spacing
and alignment.
Answer: A modal is a dialog box/popup that is displayed on top of the current page, often used
for alerts, confirmations, or forms.
Answer: A modal can be triggered using a button with the data-toggle="modal" attribute
Answer: A tooltip is a small pop-up box that appears when the user hovers over an element. It
can display additional information about the element.
Answer: Tooltips are activated using JavaScript with the $(function () { $('[data-
toggle="tooltip"]').tooltip() }) method.
Answer: Badges are small count indicators that can be used to indicate new items, unread
messages, etc., using the .badge class.
Answer: Use the .dropdown-toggle class along with the data-toggle="dropdown" attribute to
create a dropdown button.
Answer: Pagination is a component that provides navigation between pages. It uses classes
like .pagination and .page-item.
Answer: A carousel is a slideshow component for cycling through a series of content, such as
images or text.
28. How do you create a carousel in Bootstrap?
Answer: Use the .carousel, .carousel-inner, and .carousel-item classes to create a carousel, along
with the data-ride="carousel" attribute.
Answer: Bootstrap's utility API provides a set of helper classes that can be used to adjust
margins, paddings, display properties, text alignments, and more without writing custom CSS.
Answer: Spinners are used to show loading indicators. They can be created using the .spinner-
border or .spinner-grow classes.
Answer: .btn-primary is used for the main action buttons, while .btn-secondary is used for
secondary actions.
Answer: You can center content horizontally using the .justify-content-center class.
Answer: Flexbox is a layout mode in CSS that Bootstrap leverages to create flexible and
responsive layouts. Bootstrap includes classes like .d-flex, .justify-content-*, and .align-items-* to
utilize Flexbox.
Answer: The Collapse component is used to show or hide content by toggling the visibility. It can
be triggered via buttons or links.
Answer: An accordion is a series of collapsible items that allow only one item to be expanded at
a time.
Answer: Scrollspy is a plugin that automatically updates links in a navigation list based on the
scroll position. It works with the .nav component.
Answer: The media object is a flexible component used to build complex and repetitive
components like comments, tweets, etc. It includes classes like .media, .media-body, and .media-
heading.
Answer: The .sr-only class is used to hide elements from the screen but keep them accessible to
screen readers, improving accessibility.
Answer: Toasts are lightweight notifications that provide quick, feedback to the user.
Answer: A Popover is similar to a tooltip but can contain more content. It is a small overlay that
appears on top of the screen content.
Answer: Use the .list-group class to create a list group, with each item wrapped in the .list-group-
item class.
Answer: The .btn-group class is used to group a series of buttons together on a single line.
Answer: Add the .btn-group-vertical class to a .btn-group to stack the buttons vertically.
Answer: The input group allows you to prepend or append buttons, text, or other elements to a
text input.
Answer: The .d-none class is used to hide an element by setting its display property to none.
Answer: The .clearfix class is used to clear floats, ensuring that the floated elements are
contained within their container.
6.Angular js
1. What is AngularJS?
AngularJS is a JavaScript framework used to create dynamic web applications. It extends HTML
with additional attributes and binds data to HTML with expressions.
Data binding is the synchronization of data between the model (JavaScript objects) and the view
(HTML).
Directives are special markers in the DOM that tell AngularJS to attach a specified behavior to
that DOM element.
$scope is an object that refers to the application model. It acts as a glue between the controller
and the view.
MVC stands for Model-View-Controller. The model represents the data, the view displays the
data, and the controller handles the business logic.
Controllers are JavaScript functions that are used to build the application logic and control the
flow of data between the model and the view.
Services are singleton objects that are used to organize and share code across your app.
A factory is a function that returns an object. It is used to create and configure services.
$watch is used to monitor changes in the model and execute code in response to changes.
$scope is a service provided by AngularJS that is injected into controllers and other components,
whereas scope is just a plain object.
Use the .directive method on a module, and return an object that defines the directive.
$rootScope is the top-level scope that is shared across the entire AngularJS application.
The $digest cycle is the process in which AngularJS checks for changes in the model and updates
the view accordingly.
ng-model is a directive that binds the value of HTML controls (input, select, textarea) to
application data.
$http is a core AngularJS service that facilitates communication with remote HTTP servers
ng-repeat is a directive used to iterate over a collection and render HTML elements for each
item.
You can handle events using AngularJS directives like ng-click, ng-submit, etc.
ng-if removes or recreates the element in the DOM based on the condition, while ng-show
toggles the visibility of the element.
Two-way data binding, modularization, reusable components, ease of testing, and dependency
injection.
$location service parses the URL in the address bar and makes changes to the browser URL.
$timeout is a service that allows you to execute a function after a specified delay.
$q is a service that helps you run functions asynchronously and use their return values (or
exceptions) when they are done processing.
ng-bind binds the inner text content of an HTML element to the application data.
$compile service traverses the DOM and matches directives against the elements.
A SPA is a web application that loads a single HTML page and dynamically updates as the user
interacts with the app.
$interpolate is a service used to compile expressions and interpolate values into the resulting
string.
$broadcast sends an event downwards from the parent scope to all child scopes.
$emit sends an event upwards from the child scope to the parent scope.
Minify and bundle files, use $scope.$applyAsync(), reduce watchers, and use one-time bindings.
$destroy is used to remove a scope and its watchers from the AngularJS application.
Transclusion is the process of including the original content of a directive into a directive
template.
$timeout is used to execute code after a delay, and $interval is used to execute code repeatedly
at specified intervals.