Posted On April 3, 2026

MERN Stack Interview Questions with Answers for freshers

patil.sandip2490@gmail.com 0 comments
>> Uncategorized >> MERN Stack Interview Questions with Answers for freshers
mern-stack-developement

MongoDB (Database Layer)

  1. What is MongoDB?
    MongoDB is a NoSQL document-oriented database that stores data in JSON-like BSON format. It is schema-less, highly scalable, and supports flexible data models. It’s widely used in MERN stack because of its seamless integration with JavaScript.
  2. What is BSON?
    BSON (Binary JSON) is a binary representation of JSON. It supports more data types than JSON, like Date, Binary data, and is optimized for storage and retrieval in MongoDB.
  3. Difference between SQL and NoSQL?
    • SQL: Relational, structured tables, predefined schema, ACID transactions.
    • NoSQL: Non-relational, flexible schema, document/graph/column storage, scalable horizontally.
      MongoDB is NoSQL.
  4. What is a collection in MongoDB?
    A collection is like a table in SQL. It holds multiple documents (records). Collections are schema-less, so documents can have different structures.
  5. What is a document in MongoDB?
    A document is a record in MongoDB, stored in BSON format. It is equivalent to a row in SQL and consists of key-value pairs.
  6. Explain _id in MongoDB.
    Every document has a unique _id field (ObjectId by default) which acts as the primary key. It is automatically generated if not provided.
  7. How to create a database in MongoDB?

    use myDatabase

    MongoDB will create the database when a collection is first created.

  8. How to create a collection?

    db.createCollection(“users”)

  9. Difference between find() and findOne().
    • find(): Returns all matching documents in a cursor.
    • findOne(): Returns the first matching document.
  10. Explain indexing in MongoDB.
    Indexes improve query performance. For example:

    db.users.createIndex({ name: 1 }) // ascending order

  11. What are aggregation pipelines?
    Aggregation pipelines allow data processing and transformation in stages like $match, $group, $sort. Example:

    db.orders.aggregate([
      { $match: { status: “completed” } },
      { $group: { _id: “$customerId”, total: { $sum: “$amount” } } }
    ])

  12. Difference between updateOne, updateMany, replaceOne.
    • updateOne(): Updates first matching document.
    • updateMany(): Updates all matching documents.
    • replaceOne(): Replaces the whole document.
  13. Explain Mongoose.
    Mongoose is an ODM (Object Data Modeling) library for MongoDB in Node.js. It provides schemas, validation, and model abstraction.
  14. How to define a schema in Mongoose?

    const mongoose = require(‘mongoose’);
    const userSchema = new mongoose.Schema({
      name: String,
      email: String,
      password: String
    });
    const User = mongoose.model(‘User’, userSchema);

  15. Difference between save() and create() in Mongoose.
    • save(): Called on an instance of a model; triggers middleware.
    • create(): Directly creates a new document; faster but less flexible.
  16. What is populate() in Mongoose?
    populate() allows you to reference documents from another collection. Example:

    Post.find().populate(‘author’).exec()

  17. Explain MongoDB transactions.
    MongoDB supports multi-document ACID transactions in replica sets. Example:

    const session = await mongoose.startSession();
    session.startTransaction();
    // operations
    await session.commitTransaction();
    session.endSession();

  18. Difference between embedded documents and references.
    • Embedded: Data stored inside a document (fast, denormalized).
    • Reference: Stores ObjectId of another document (normalized, flexible).
  19. How to handle relations in MongoDB?
    Use embedded documents or references with populate().
  20. Explain capped collections.
    Capped collections are fixed-size, circular collections, ideal for logging.

 

Express.js (Backend Layer)

  1. What is Express.js?
    Express.js is a Node.js framework for building web applications and APIs. It simplifies routing, middleware, and request handling.
  2. How to create a simple Express server?

    const express = require(‘express’);
    const app = express();
    app.get(‘/’, (req, res) => res.send(‘Hello MERN’));
    app.listen(3000, () => console.log(‘Server running’));

  3. What is middleware in Express?
    Middleware is a function that has access to request, response, and next().
    Example:

    app.use((req, res, next) => {
      console.log(‘Request URL:’, req.url);
      next();
    });

  4. Difference between app.use and app.get/post.
    • app.use(): For middleware, applies to all routes or a path.
    • app.get/post(): Defines HTTP GET or POST routes.
  5. How to handle errors in Express?

    app.use((err, req, res, next) => {
      res.status(500).json({ error: err.message });
    });

  6. What is routing in Express?
    Routing maps HTTP requests to functions based on URL paths and methods.
  7. How to parse JSON in Express?

    app.use(express.json());

  8. What are route parameters?
    Variables in URL path. Example:

    app.get(‘/user/:id’, (req, res) => {
      res.send(req.params.id);
    });

  9. What are query parameters?
    Parameters in URL after ?. Example: /user?id=123 → req.query.id.
  10. Explain CORS and handling in Express.
    CORS allows cross-origin requests. In Express:

    const cors = require(‘cors’);
    app.use(cors());

  11. How to serve static files in Express?

    app.use(express.static(‘public’));

  12. Explain Express Router.
    Router allows modular routing:

    const router = express.Router();
    router.get(‘/users’, (req, res) => res.send(‘Users’));
    app.use(‘/api’, router);

  13. How to connect Express with MongoDB?

    const mongoose = require(‘mongoose’);
    mongoose.connect(‘mongodb://localhost:27017/mernDB’);

  14. Difference between PUT and PATCH in Express.
    • PUT: Replaces the whole resource.
    • PATCH: Updates specific fields.
  15. What is JWT and how to use in Express?
    JWT (JSON Web Token) is used for authentication. Example:

    const jwt = require(‘jsonwebtoken’);
    const token = jwt.sign({ id: user._id }, ‘secretKey’, { expiresIn: ‘1h’ });

  16. Explain middleware chaining in Express.
    Multiple middleware can be executed in order using next().

    app.get(‘/route’, mw1, mw2, (req,res)=>res.send(‘done’));

  17. How to handle file uploads in Express?
    Use multer library:

    const multer = require(‘multer’);
    const upload = multer({ dest: ‘uploads/’ });
    app.post(‘/upload’, upload.single(‘file’), (req, res) => res.send(‘File uploaded’));

  18. Difference between res.send, res.json, res.end.
    • res.send(): Sends string, object, or buffer.
    • res.json(): Sends JSON response.
    • res.end(): Ends response without data.
  19. What are environment variables?
    Sensitive or config data stored in .env. Example:

    PORT=5000
    DB_URL=mongodb://localhost:27017/mernDB

    Access in Node: process.env.PORT.

  20. How to handle 404 routes?

    app.use((req, res) => res.status(404).send(‘Not Found’));

React.js (Frontend Layer)

  1. What is React.js?
    React.js is a JavaScript library for building interactive user interfaces. It uses component-based architecture, virtual DOM, and unidirectional data flow.
  2. Difference between React and Angular?React: Library, uses JSX, component-based, unidirectional data flow.Angular: Framework, uses TypeScript, MVC pattern, two-way data binding.
  3. What is JSX?
    JSX is a JavaScript XML syntax that allows you to write HTML inside JavaScript. Example:

    const element = <h1>Hello React</h1>;

  4. What is a component?
    A component is a reusable UI element in React.Functional Component: Function-based.Class Component: ES6 class-based.
  5. Explain props in React.
    Props (short for properties) are read-only inputs passed from parent to child.

    function Child({ name }) {
      return <h1>Hello {name}</h1>;
    }

  6. What is state in React?
    State is mutable data managed inside a component. Updating state re-renders the component.

    const [count, setCount] = useState(0);

  7. Difference between state and props?Props: Read-only, from parent, immutable.State: Mutable, local to component, managed by the component.
  8. What are React Hooks?
    Hooks allow functional components to use state and lifecycle features.
    Examples: useState, useEffect, useRef, useContext.
  9. Explain useEffect.
    useEffect handles side effects like API calls, DOM updates, and subscriptions.

    useEffect(() => {
      fetchData();
    }, [dependencyArray]);

  10. Explain the virtual DOM.
    Virtual DOM is a lightweight copy of the real DOM. React updates the virtual DOM first and then efficiently updates only changed elements in the real DOM.
  11. Difference between controlled and uncontrolled components.Controlled: Form inputs controlled via state.Uncontrolled: Form inputs managed by DOM using refs.
  12. How to handle forms in React?
    Use state for controlled components:

    <input value={name} onChange={(e)=>setName(e.target.value)} />

  13. What is lifting state up?
    Sharing state between components by moving it to the nearest common parent.
  14. Explain React Router.
    React Router manages client-side routing. Example:

    import { BrowserRouter, Routes, Route } from ‘react-router-dom’;
    <BrowserRouter>
      <Routes>
        <Route path=”/” element={<Home />} />
        <Route path=”/about” element={<About />} />
      </Routes>
    </BrowserRouter>

  15. Difference between React Router v5 and v6.v6 uses <Routes> instead of <Switch>.Nested routes and element props replaced component.
  16. What is Context API?
    Allows sharing global state without prop drilling:

    const ThemeContext = React.createContext();
    <ThemeContext.Provider value={theme}>…</ThemeContext.Provider>

  17. What is Redux?
    Redux is a state management library for React that uses a central store to manage global state.
  18. Explain Redux flow.
  19. Action dispatched → 2. Reducer updates state → 3. Store notifies components.
  20. Difference between Redux and Context API?Context API: Simple global state, best for small apps.Redux: Robust, scalable, middleware support, good for complex apps.
  21. Explain React.memo.
    React.memo prevents unnecessary re-renders by memoizing the component.
  22. What is useRef?
    useRef stores mutable references to DOM elements or variables that persist between renders.
  23. What is useCallback and useMemo?
  • useCallback: Memoizes functions.
  • useMemo: Memoizes computed values.
  1. Difference between class and functional components.
  • Class: State, lifecycle methods, older style.
  • Functional: Hooks, simpler, modern approach.
  1. Explain lifecycle methods in React.
    Class components: componentDidMount, componentDidUpdate, componentWillUnmount.
    Functional: Use useEffect.
  2. What are higher-order components (HOC)?
    HOC are functions that take a component and return a new enhanced component.
  3. Difference between key and ref in React.
  • key: Unique identifier for list items, used for rendering optimization.
  • ref: Access DOM element or component instance.
  1. What is suspense and lazy loading?
    React.lazy + Suspense allows code splitting and dynamic component loading.
  2. Explain portals in React.
    Portals render a child component outside the DOM hierarchy of its parent.
  3. How to optimize React performance?
  • Memoization (React.memo, useCallback)
  • Avoid unnecessary re-renders
  • Code splitting and lazy loading
  • Use keys in lists
  1. What is prop drilling? How to avoid it?
    Passing props through multiple levels unnecessarily. Avoid with Context API or Redux.

Node.js (Backend Layer)

  1. What is Node.js?
    Node.js is a JavaScript runtime built on Chrome’s V8 engine. It allows JS to run on the server-side with non-blocking, event-driven architecture.
  2. Difference between Node.js and traditional server?
  • Node.js: Non-blocking, single-threaded, event-driven.
  • Traditional server: Multi-threaded, blocking I/O.
  1. Explain event loop in Node.js.
    The event loop handles asynchronous operations in a single thread, allowing non-blocking I/O.
  2. What are streams in Node.js?
    Streams handle large data efficiently without loading everything in memory. Types: readable, writable, duplex, transform.
  3. What is npm?
    Node Package Manager, used to install, manage, and share Node.js packages.
  4. Difference between require() and import?
  • require(): CommonJS, used in Node.js.
  • import: ES6 module syntax.
  1. What is middleware in Node.js?
    Middleware is a function executed during request-response cycle, typically in Express.js.
  2. Explain error handling in Node.js.
    Use try/catch for synchronous code and .catch() or async/await for async code.
  3. How to connect Node.js with MongoDB?
    Use mongoose.connect(DB_URL) or native MongoClient.
  4. What is package.json?
    package.json stores project metadata, dependencies, scripts, and config.
  5. Explain asynchronous programming in Node.js.
    Node.js uses callbacks, promises, and async/await for non-blocking operations.
  6. What is buffer in Node.js?
    Buffer stores binary data while reading files or working with TCP streams.
  7. Difference between process.nextTick() and setImmediate()
  • process.nextTick(): Executes before the next event loop.
  • setImmediate(): Executes in the next event loop iteration.
  1. How to secure Node.js applications?
  • Use HTTPS
  • Sanitize inputs
  • JWT authentication
  • Helmet, rate limiting, CORS
  1. How to deploy Node.js app?
  • Platforms: Heroku, Vercel, Render, AWS EC2
  • Build: npm install, node server.js, use PM2 for process management.

Full MERN Stack Integration

  1. What is the MERN stack?
    MERN = MongoDB, Express.js, React.js, Node.js. Full-stack JavaScript for building scalable web apps.
  2. How does data flow in MERN?React sends HTTP request to Express Express handles API and queries MongoDB MongoDB returns data to Express Express sends response to React React updates UI
  3. How to call API from React?

    fetch(‘/api/users’)
      .then(res => res.json())
      .then(data => setUsers(data));

  1. How to handle JWT in MERN?
  • Generate JWT in Node.js after login
  • Send to React, store in localStorage or cookie
  • Include JWT in Authorization header for protected routes
  1. Explain protected routes in MERN.
  • Backend: Middleware checks JWT before allowing API access
  • Frontend: React checks auth state before rendering component
  1. What is CORS problem in MERN?
    Browser blocks requests from different origin. Solved by cors middleware in Express.
  2. How to connect React with Express?
  • Option 1: React frontend calls backend via fetch or axios
  • Option 2: Serve React build via Express:

    app.use(express.static(‘client/build’));
    app.get(‘*’, (req,res) => res.sendFile(path.resolve(‘client’,’build’,’index.html’)));

  1. What is dotenv in MERN?
    .env file stores environment variables like DB URL, JWT secret. Node.js accesses via process.env.
  2. How to handle errors in MERN?
  • Backend: Use try/catch and middleware
  • Frontend: Use try/catch in API calls, show user-friendly messages
  1. What is Redux in MERN?
    Redux is often used to manage global state across React components, especially for user authentication, cart, or settings.
  2. How to deploy MERN stack app?
  • Build React: npm run build
  • Serve via Express or host separately
  • Deploy MongoDB Atlas for database
  • Deploy Node.js server on Heroku, Render, or AWS
  1. What are WebSockets and Socket.io?
    Used for real-time communication in MERN apps, like chat apps or live notifications.
  2. How to handle file uploads in MERN?
  • Backend: multer saves files
  • Frontend: FormData API to send files via axios
  1. Explain pagination in MERN.
    Backend: Use skip and limit in MongoDB query
    Frontend: Display page numbers, call API with page parameter
  2. Tips for optimizing MERN stack app
  • Use indexes in MongoDB
  • Optimize React rendering (memoization)
  • Enable compression in Express
  • Lazy load routes and components
  • Use CDN for static assets

 

    Leave a Reply

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

    Related Post

    Noise Pulse Hyper Smart Watch – Rose Pink

    Product Highlights Stylish • Smart • Powerful Upgrade your lifestyle with the premium Noise Pulse…

    School Products List

      1. Hook / Attention Line “Back to School ! Make sure your child has…

    Top 100 WordPress Interview Questions & Answers

    Basic WordPress Q&A 1. What is WordPress? WordPress is an open-source Content Management System (CMS)…