Fullstack Training Center

Mern Stack Interview Questions

Mern Stack Interview Questions Freshers

1. What is MongoDB?
MongoDB is a NoSQL, document-oriented database that stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time.

2. What is a collection in MongoDB?
A collection is a group of MongoDB documents, similar to a table in relational databases.

3. What is a document in MongoDB?
A document in MongoDB is a single record stored in a collection, represented in a BSON format (Binary JSON).

4. How do you connect MongoDB with Node.js?
You can connect MongoDB to Node.js using the mongodb or mongoose library. Example using mongoose:
const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost:27017/dbname’, { useNewUrlParser: true, useUnifiedTopology: true });

const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost:27017/dbname’, { useNewUrlParser: true, useUnifiedTopology: true });

5. What is Mongoose in MongoDB?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js that provides a schema-based solution to model your application data.

6. How do you create a schema in Mongoose?Example of a schema in Mongoose:
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});

7. What are indexes in MongoDB, and why are they used?
Indexes in MongoDB improve the speed of search queries by creating a data structure that holds a small portion of the data. Indexes are particularly useful for large datasets.

8. What is the process for creating a model in Mongoose?
Mongoose model is created by compiling a schema:
const User = mongoose.model(‘User’, userSchema);

9. What is the find method in MongoDB?
The find method is used to query documents from a collection that match a given condition. Example:
User.find({ name: ‘John’ });

10. To update a document in MongoDB, what steps should be taken?
Use updateOne, updateMany, or findByIdAndUpdate. Example:
User.updateOne({ name: ‘John’ }, { $set: { age: 30 } });

11. What is the aggregate function in MongoDB?
The aggregate function is used for data aggregation operations like grouping, filtering, and calculating values.

12. What is the difference between findOne and findById in MongoDB?
findOne finds the first document that matches the query, whereas findById specifically looks for a document by its _id field.

13. How does MongoDB ensure data consistency?
MongoDB uses journaling to ensure data consistency. It also supports transactions that maintain the atomicity of multiple operations.

14. What are the different types of relationships in MongoDB?
Relationships in MongoDB can be:
Embedded: Storing related data in the same document.
Referenced: Using ObjectId to reference documents in other collections.

15. How do you implement one-to-many relationships in MongoDB?
You can implement one-to-many relationships by embedding documents or referencing other documents using an array of ObjectIds.

16. What is populate in Mongoose?
The term “populate” refers to the process of substituting designated paths within a document with documents sourced from alternative collections. This functionality is particularly beneficial for managing referenced relationships.

17. What is the procedure for removing a document in MongoDB?
Use methods like deleteOne, deleteMany, or findByIdAndDelete. Example:
User.deleteOne({ _id: ‘5f50c31b1c9d440000a6fb47’ });

18. What is a replica set in MongoDB?
A replica set is a group of MongoDB servers that maintain the same data, providing redundancy and high availability.

19. What is sharding in MongoDB?
Sharding is the technique employed by MongoDB to allocate data across various servers. This approach enables MongoDB to manage extensive datasets and perform operations with high throughput.

20. How do you perform a text search in MongoDB?
You need to create a text index and then perform a search:
db.collection.createIndex({ content: ‘text’ });
db.collection.find({ $text: { $search: ‘keyword’ } });

21. What is Express.js?
Express.js is a minimal, flexible Node.js web application framework that provides tools for building web applications and APIs.

22. How do you create a simple server using Express.js?
const express = require(‘express’);
const app = express();
app.get(‘/’, (req, res) => res.send(‘Hello World!’));
app.listen(3000);

23. What is middleware in Express.js?
Middleware refers to functions that can access the request object, the response object, and the subsequent middleware function within the application’s request-response cycle.

24. How do you handle static files in Express.js?
Utilize the express.static middleware to deliver static files.
app.use(express.static(‘public’));

25. How can you set up a route in Express.js?
Routing refers to how an application’s endpoints (URIs) respond to client requests.

26. How can you set up a route in Express.js?
app.get(‘/users’, (req, res) => {
res.send(‘User list’);
});

27. How do you handle POST requests in Express.js?
app.post(‘/users’, (req, res) => {
res.send(‘User created’);
});

app.post(‘/users’, (req, res) => {
res.send(‘User created’);
});

28. How do you parse JSON in Express.js?
Use express.json() middleware:
app.use(express.json());

29. How do you handle errors in Express.js?
A: Use a custom error-handling middleware:
app.use((err, req, res, next) => {
res.status(500).send(‘Something went wrong!’);
});

30. How do you handle URL parameters in Express.js?
app.get(‘/users/:id’, (req, res) => {
res.send(`User ID: ${req.params.id}`);
});

31. What is next() function in Express.js?
next() is used to pass control to the next middleware function in the stack.

32. How do you implement CORS in Express.js?
Use the cors middleware:
const cors = require(‘cors’);
app.use(cors());

33. How do you secure an Express.js application?
Some security measures include:
Using HTTPS.
Using environment variables for sensitive data.
Validating user input.
Implementing rate limiting.

34. How do you handle file uploads in Express.js?
Use the multer middleware for handling file uploads.

35. What are route parameters in Express.js?
Route parameters are named URL segments that capture values at specified positions in the URL.

36. How do you implement sessions in Express.js?
A: Use express-session middleware:
const session = require(‘express-session’);
app.use(session({ secret: ‘mysecret’, resave: false, saveUninitialized: true }));

37. How do you redirect a user in Express.js?
res.redirect(‘/new-url’);

38. What is body-parser in Express.js?
body-parser is middleware for parsing request bodies, now included in Express 4.x as express.json() and express.urlencoded().

39. How do you implement authentication in Express.js?
You can use strategies like JWT or OAuth with middleware like passport.js or express-jwt.

40. How do you handle query parameters in Express.js?
Query parameters can be accessed using req.query:
app.get(‘/search’, (req, res) => {
res.send(`Query: ${req.query.q}`);
});

41. What is React?
React is a JavaScript library for building user interfaces, primarily used for single-page applications.

42. What is JSX in React?
JSX is a syntax extension for JavaScript that looks similar to HTML and is used to describe the UI structure in React components.

43. What is a component in React?
A component in React is a reusable UI element that renders part of the user interface.

44. What are props in React?
Props are short for properties and are used to pass data from parent to child components.

45. What is state in React?
State is a built-in object that holds dynamic values that can change over time in a component.

46. What is the difference between functional and class components in React?
Class components use ES6 class syntax and can have state and lifecycle methods, whereas functional components are simpler and use hooks for state and lifecycle features.

47. What is the useState hook in React?
useState is a React hook that lets you add state to functional components.

48. How do you handle events in React?
Events in React are handled similar to HTML events but use camelCase. Example:
<button onClick={handleClick}>Click me</button>

49. What is the useEffect hook in React?
useEffect is used to perform side effects in functional components, like data fetching or updating the DOM.

50. What is conditional rendering in React?
Conditional rendering allows you to render different components or elements based on certain conditions using if, &&, or ternary operators.

Mern Stack Interview Questions For Experienced

51. How do you render a list of items in React?
const items = [1, 2, 3];
return (
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
);

52. What is the useContext hook in React?
useContext allows you to access the context value without needing to pass props down through every level of the component tree.

53. What is React Router?
React Router is a library for handling navigation and routing in React applications.

54. How do you implement routing in React?
You can implement routing using react-router-dom:
<BrowserRouter>
<Route path=”/about” component={About} />
</BrowserRouter>

55. What are keys in React, and why are they important?
Keys are unique identifiers for elements in lists, used by React to optimize re-rendering by tracking changes more efficiently.

56. How do you create a form in React?
Example of a controlled form:
const [value, setValue] = useState(”);
return <input type=”text” value={value} onChange={e => setValue(e.target.value)} />;

57. What is a higher-order component (HOC) in React?
An HOC is a function that takes a component and returns a new component, commonly used for reusing component logic.

58. What is the difference between controlled and uncontrolled components in React?
Controlled components have their value controlled by React via state, while uncontrolled components manage their own state via the DOM.

59. How do you optimize performance in a React app?
Some techniques include:
Using React.memo for memoization.
Lazy loading components.
Using the useCallback and useMemo hooks.

60. What is a React Fragment?
A React Fragment is a wrapper that allows grouping multiple elements without adding an extra DOM node:
return <React.Fragment>…</React.Fragment>;

61. What is a custom hook in React?
A custom hook is a JavaScript function that starts with use and allows you to extract and reuse component logic.

62. What are React lifecycle methods?
Lifecycle methods are hooks that allow you to run code at specific times in a component’s lifecycle, like componentDidMount, componentDidUpdate, and componentWillUnmount.

63. How do you manage state globally in React?
You can manage state globally using React Context API or libraries like Redux.

64. What is Redux? 

Redux is a predictable state container for JavaScript apps, often used with React for global state management.

65. What is the Context API in React?
The Context API provides a way to pass data through the component tree without passing props manually at every level.

66. What is Prop Drilling in React?
Prop drilling refers to the process of passing props down through multiple components in order to reach a deeply nested component.

67. What are controlled components in React?
Controlled components are form elements where the value is controlled by the component’s state.

68. What are React portals?
React portals allow you to render children into a DOM node outside the parent component’s hierarchy.

69. What is lazy loading in React?
Lazy loading is a technique that allows you to load components only when they are needed, improving performance. Example:
const LazyComponent = React.lazy(() => import(‘./LazyComponent’));

70. How do you handle errors in React?
Use Error Boundaries to catch errors in React:
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
// Handle error
}
}

71. What is Node.js?
Node.js is a runtime environment for executing JavaScript on the server-side, built on the V8 JavaScript engine.

72. How does Node.js handle asynchronous code?
A: Node.js uses an event-driven, non-blocking I/O model, meaning operations like file reads and network requests are handled asynchronously using callbacks, promises, or async/await.

73. What is npm?
npm (Node Package Manager) is a package manager for Node.js that allows developers to install, share, and manage project dependencies.

74. How do you initialize a Node.js project?
Run npm init in the terminal to create a package.json file for the project.

75. What is the difference between require and import in Node.js?
require is the CommonJS way of importing modules in Node.js, whereas import is the ES6 module syntax.

76. What is an event loop in Node.js?
The event loop is the mechanism that allows Node.js to perform non-blocking I/O operations by offloading tasks to the operating system.

77. What is a callback function in Node.js?
A callback function is a function passed as an argument to another function, to be executed once the asynchronous task is completed.

78. How do you handle errors in Node.js?
Errors are typically handled using callbacks with an error argument, try-catch for synchronous code, and .catch() for promises.

79. What are streams in Node.js?
Streams are objects that allow you to read data from or write data to a source in a continuous flow. There are four types of streams: Readable, Writable, Duplex, and Transform streams.

80. How do you read a file in Node.js?
const fs = require(‘fs’);
fs.readFile(‘file.txt’, ‘utf8’, (err, data) => {
if (err) throw err;
console.log(data);
});

81. What is middleware in Node.js?
Middleware functions are functions that have access to the request and response objects in an application, allowing you to perform tasks like logging, authentication, or request parsing.

82. What is process in Node.js?
process is a global object in Node.js that provides information and control over the current Node.js process, like handling environment variables, reading command-line arguments, etc.

83. What is the path module in Node.js?
The path module provides utilities for working with file and directory paths.

84. What is a buffer in Node.js?
Buffers are used to handle binary data in Node.js, especially when working with streams or network protocols.

85. What is child_process in Node.js?
child_process allows you to spawn new processes, execute shell commands, and manage those processes from within a Node.js application.

86. How do you make HTTP requests in Node.js?
You can use the http module or external libraries like axios or node-fetch.

87. What are environment variables in Node.js?
Environment variables are variables set in the environment where the Node.js process is running, typically used for configuration. They can be accessed via process.env.

88. What is express-validator in Node.js?
express-validator is a middleware for validating and sanitizing incoming requests in Express applications.

89. What are Node.js clusters?
Clusters in Node.js allow you to create child processes that share the same server port, helping to scale the application across multiple CPU cores.

90. What is nodemon in Node.js?
nodemon is a tool that automatically restarts a Node.js application when it detects file changes, helping in development.

91. What is the purpose of the require function in Node.js?
The require function is used to include modules (local or from npm) in a Node.js application.

92. What is jsonwebtoken in Node.js?
jsonwebtoken is a library for generating and verifying JSON Web Tokens (JWT), often used for authentication.

93. How do you handle file uploads in Node.js?
You can handle file uploads using the multer middleware.

94. What is a promise in Node.js?
A promise is an object representing the eventual completion or failure of an asynchronous operation.

95. What is async/await in Node.js?
async/await is syntactic sugar built on top of promises, allowing asynchronous code to be written in a synchronous style.

96. How do you deploy a Node.js application?
You can deploy a Node.js application using services like Heroku, DigitalOcean, or AWS. You typically push the code to a Git repository and use environment-specific configurations for setup.


97. What is rate-limiting in Node.js?

Rate-limiting is a mechanism to control the number of requests a client can make to your server in a given period, typically implemented to prevent abuse or denial of service attacks.

98. How do you implement authentication in Node.js?
A: Authentication in Node.js can be implemented using JSON Web Tokens (JWT), OAuth, or using libraries like passport.js.

99. What is the cluster module in Node.js?
A: The cluster module allows you to create child processes (workers) that share the same server port, useful for utilizing multi-core systems to increase application performance.

Scroll to Top