Skip to content

MERN Stack Interview Questions in Pune

36 practice questions with answers for MERN Stack interviews in Pune.

MERN Stack jobs in Pune

Pune combines IT-services campuses in Hinjewadi and Kharadi with product, automotive and BFSI technology centres. It has a large mid-level job market for data and QA roles, and interviews are often practical and project-based.

Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Pune.

Solved for PuneStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Write a debounce function in JavaScript.

Save to ▾
Show answer
Debounce delays a call until a quiet period has passed. Each new call clears the previous timer. function debounce(fn, delay = 300) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const onSearch = debounce((q) => fetchResults(q), 400); It relies on a closure over timer and keeps this and arguments intact.
02

How should a component display data loaded from an API in a user-friendly way?

Save to ▾
Show answer
Handle every state explicitly: show a skeleton or spinner while loading, an error message with a retry button if the request fails, an empty state with guidance when there is no data, and the content otherwise. Keep these in state variables or use a library like TanStack Query that provides isPending, isError and data. Never leave a blank screen or crash on undefined data.
03

Your app needs user, editor and admin roles with different permissions. How would you implement it?

Save to ▾
Show answer
Store a role, or a list of permissions, on the user document and include it in the token or load it in the auth middleware. Write an authorize middleware that checks allowed roles or permissions per route, for example authorize('admin'). Add ownership checks in services, such as an editor editing only their own articles. In React, hide buttons by role for user experience, but always enforce rules on the server.
04

Show the use of $push, $addToSet, $inc and $pull update operators.

Save to ▾
Show answer
Update operators change parts of a document atomically: db.posts.updateOne({ _id: id }, { $inc: { views: 1 } }) db.posts.updateOne({ _id: id }, { $addToSet: { tags: 'mongodb' } }) db.posts.updateOne({ _id: id }, { $push: { comments: { text: 'Nice', at: new Date() } } }) db.posts.updateOne({ _id: id }, { $pull: { tags: 'old' } }) $addToSet avoids duplicates, while $push always appends. Add $slice inside $push to cap an array's length.
05

Why do applications use both access tokens and refresh tokens?

Save to ▾
Show answer
The access token is short-lived, for example 15 minutes, and is sent with every API request, so if stolen it is useful only briefly. The refresh token is long-lived, stored more securely in an httpOnly cookie, and is used only at a refresh endpoint to get new access tokens. Refresh tokens should be stored server-side or hashed so they can be revoked, and rotated on every use to detect theft.
06

What is Node.js and how does it handle many requests on a single thread?

Save to ▾
Show answer
Node.js is a JavaScript runtime built on the V8 engine and libuv. Your JavaScript runs on one main thread, but I/O such as network calls, file reads and database queries is non-blocking. Node hands that work to the operating system or the libuv thread pool and continues with other requests; callbacks run when results are ready. This makes it efficient for I/O-heavy APIs, but weak for CPU-heavy work.
07

What is the difference between server state and client state, and why use a library like TanStack Query?

Save to ▾
Show answer
Client state is UI data owned by the browser, like modal open or selected tab. Server state lives in the database, can be changed by others, and is only a cached copy in the browser. TanStack Query manages server state with caching, deduplication, background refetching, retries, pagination and mutations with cache invalidation. This removes much hand-written useEffect fetching and stops global stores from holding stale API data.
08

What is the output order of console.log('A'), setTimeout(() => console.log('B'), 0), Promise.resolve().then(() => console.log('C')) and console.log('D')?

Save to ▾
Show answer
The output is A, D, C, B. A and D are synchronous and run immediately on the call stack. The Promise callback C goes into the microtask queue, and the setTimeout callback B goes into the macrotask queue. After the synchronous code finishes, the event loop drains all microtasks first, printing C, and only then runs the timer callback, printing B, even with a 0 ms delay.
09

What practical steps do you take to sanitise and validate input in an Express and MongoDB API?

Save to ▾
Show answer
Validate every request body, params and query against a schema with zod or Joi, rejecting unknown fields and wrong types. Apply body size limits with express.json({ limit: '100kb' }). Strip MongoDB operator keys from input with a small sanitising middleware or library, and keep Mongoose strict mode on. Escape or sanitise HTML with DOMPurify before storing rich text, and validate ObjectIds before querying.
10

Write basic CRUD commands in mongosh for a users collection.

Save to ▾
Show answer
Core shell commands: db.users.insertOne({ name: 'Riya', email: 'riya@mail.com', age: 24 }) db.users.find({ age: { $gte: 21 } }, { name: 1, email: 1, _id: 0 }) db.users.updateOne({ email: 'riya@mail.com' }, { $set: { age: 25 } }) db.users.deleteMany({ isActive: false }) db.users.countDocuments({ city: 'Pune' }) The second argument of find is a projection that controls which fields are returned.
11

How do you add a timeout to a fetch call in Node.js?

Save to ▾
Show answer
Node 18 and later ship a global fetch. Use AbortSignal.timeout to cancel slow requests. async function getJSON(url) { try { const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } catch (err) { if (err.name === 'TimeoutError') console.error('Request timed out'); throw err; } } Without a timeout, a hung upstream can hold connections open indefinitely.
12

Should you store a JWT in localStorage or in an httpOnly cookie?

Save to ▾
Show answer
localStorage is readable by any JavaScript on the page, so an XSS bug can steal the token. An httpOnly, Secure cookie cannot be read by JavaScript, which protects against token theft through XSS, but cookies are sent automatically, so you must defend against CSRF with SameSite=Lax or Strict and CSRF tokens where needed. A common pattern keeps the refresh token in an httpOnly cookie and the access token in memory.
13

Read a JSON file and write an updated version using fs/promises and async/await.

Save to ▾
Show answer
The promise-based fs API keeps code clean and non-blocking. import { readFile, writeFile } from 'node:fs/promises'; async function addUser(user) { try { const data = JSON.parse(await readFile('users.json', 'utf8')); data.push(user); await writeFile('users.json', JSON.stringify(data, null, 2)); } catch (err) { console.error('Failed to update file', err); throw err; } } Avoid readFileSync inside request handlers because it blocks the event loop.
14

Write an asyncHandler wrapper for Express 4 route handlers.

Save to ▾
Show answer
It catches rejected Promises and forwards them to error middleware. const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); router.get('/:id', asyncHandler(async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).json({ message: 'Not found' }); res.json(user); })); Express 5 does this automatically, but many existing codebases still use this pattern.
15

Why do you want to work as a MERN stack developer?

Save to ▾
Show answer
I enjoy building complete products, and MERN lets me use one language, JavaScript, across the database queries, the API and the user interface. In my projects, such as a job portal with React, Express and MongoDB, I liked seeing a feature go from schema to screen. The stack is widely used by startups and service companies in India, and I want to grow into a full stack engineer who owns features end to end.
16

Write a central error-handling middleware with a custom AppError class.

Save to ▾
Show answer
One handler keeps responses consistent. class AppError extends Error { constructor(message, statusCode = 500) { super(message); this.statusCode = statusCode; this.isOperational = true; } } function errorHandler(err, req, res, next) { if (err.code === 11000) err = new AppError('Duplicate value', 409); const status = err.statusCode || 500; res.status(status).json({ message: err.isOperational ? err.message : 'Something went wrong' }); } app.use(errorHandler); // register last
17

Write a controlled login form that submits to an API.

Save to ▾
Show answer
One state object and a shared change handler. function LoginForm() { const [form, setForm] = useState({ email: '', password: '' }); const onChange = (e) => setForm({ ...form, [e.target.name]: e.target.value }); const onSubmit = async (e) => { e.preventDefault(); const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) }); if (!res.ok) alert('Invalid credentials'); }; return ( <form onSubmit={onSubmit}> <input name='email' value={form.email} onChange={onChange} /> <input name='password' type='password' value={form.password} onChange={onChange} /> <button>Login</button> </form> ); }
18

How do class component lifecycle methods map to hooks?

Save to ▾
Show answer
componentDidMount maps to useEffect with an empty dependency array. componentDidUpdate maps to useEffect with specific dependencies. componentWillUnmount maps to the cleanup function returned from useEffect. shouldComponentUpdate is roughly React.memo, and getDerivedStateFromProps is usually replaced by computing values during render. The mindset shifts from lifecycle moments to synchronising with external systems whenever certain values change.
19

Write an aggregation that counts orders and sums revenue per status.

Save to ▾
Show answer
Group by status and sort by revenue. db.orders.aggregate([ { $match: { createdAt: { $gte: ISODate('2026-01-01') } } }, { $group: { _id: '$status', orders: { $sum: 1 }, revenue: { $sum: '$amount' } } }, { $sort: { revenue: -1 } }, { $project: { status: '$_id', orders: 1, revenue: 1, _id: 0 } } ]) In Mongoose the same array goes into Order.aggregate([...]).
20

How does React protect against XSS and where can XSS still happen?

Save to ▾
Show answer
React escapes values rendered in JSX, so user text containing script tags is shown as text, not executed. XSS can still happen through dangerouslySetInnerHTML with unsanitised HTML, javascript: URLs in href attributes, injecting user data into script tags during SSR, or unsafe third-party scripts. Sanitise any HTML with DOMPurify, validate URLs, set a Content Security Policy, and keep tokens out of JavaScript-readable storage.
21

Fast typing in a search box sometimes shows results for an older query. What causes this and how do you fix it?

Save to ▾
Show answer
It is a race condition: responses arrive out of order, so a slow earlier request overwrites results of a newer one. In the effect, use an AbortController and abort the previous request in the cleanup, or keep an ignore flag set to true during cleanup and skip setState when it is set. Debouncing reduces requests, and TanStack Query handles this automatically by keying results to the query.
22

How would you structure the folders of a production Express API?

Save to ▾
Show answer
A layered structure keeps responsibilities clear: src/routes for route definitions, src/controllers for request and response handling, src/services for business logic, src/models for Mongoose schemas, src/middlewares for auth, validation and errors, src/config for environment and database setup, src/utils for helpers, and tests alongside or in a tests folder. Keep app.js, which builds the app, separate from server.js, which listens, so tests can import the app.
23

Attackers are trying thousands of passwords on your login endpoint. How do you defend it?

Save to ▾
Show answer
Apply strict rate limits on login per IP and per account using a shared Redis store, add progressive delays or temporary account lockout after several failures, and show a CAPTCHA after repeated attempts. Return a generic error message so attackers cannot tell whether an email exists. Log and alert on spikes, check for breached passwords at signup, and offer two-factor authentication for sensitive accounts.
24

A MongoDB query on an orders collection takes 3 seconds. How do you diagnose and fix it?

Save to ▾
Show answer
Run the query with .explain('executionStats') and check whether the winning plan is COLLSCAN and how totalDocsExamined compares to nReturned. Create an index matching the filter and sort, following ESR, and confirm it becomes IXSCAN. Also project only needed fields, add limits, use lean in Mongoose, and check the profiler or Atlas Performance Advisor for other slow queries. Re-test with production-like data volume.
25

What are a Mongoose schema and model, and how does validation work?

Save to ▾
Show answer
A schema defines the shape of documents: field types, defaults, required flags, validators, indexes and options like timestamps. A model is compiled from a schema with mongoose.model('User', userSchema) and provides query methods like find, create and updateOne. Built-in validators include required, min, max, enum and match, and you can add custom validators. Validation runs on save and create; for updates, set runValidators: true.
26

Tell me about a time you had to deliver a frontend feature under a tight deadline.

Save to ▾
Show answer
Situation: a client demo was moved two days earlier and our filters page was half done. Task: deliver a working version in time. Action: I agreed a reduced scope with the lead, reused existing components, built the three most-used filters first and wrote quick tests for them, and kept the team updated each evening. Result: the demo went well and the remaining filters shipped in the next sprint.
27

Compare offset-based and cursor-based pagination for an API.

Save to ▾
Show answer
Offset pagination uses page and limit, translating to skip and limit in MongoDB. It is simple and allows jumping to page 10, but gets slower on large collections and can skip or repeat items when data changes. Cursor pagination returns items after a stable sorted value, such as the last _id or createdAt, using an indexed range query. It stays fast and consistent, ideal for infinite scroll feeds.
28

A search box fires an API request on every keystroke and overloads the backend. How would you solve it?

Save to ▾
Show answer
Debounce the input so the request goes out only after the user stops typing for around 300 ms. Also skip very short queries, cancel the previous request with AbortController so stale responses cannot overwrite newer ones, and cache recent results. On the server side, add rate limiting and an index on the searched field. Throttling is the alternative when you need periodic updates, like scroll tracking.
29

What is a custom hook and what rules must hooks follow?

Save to ▾
Show answer
A custom hook is a function whose name starts with use and that calls other hooks to package reusable stateful logic, such as useFetch, useDebounce or useAuth. Each component using it gets its own state. Hooks must be called at the top level of a component or another hook, never inside conditions, loops or nested functions, so React can match state by call order. The eslint-plugin-react-hooks rules enforce this.
30

What does lean() do in Mongoose and when should you use it?

Save to ▾
Show answer
By default Mongoose queries return full documents with change tracking, getters, virtuals and methods like save. Calling .lean() returns plain JavaScript objects, which uses much less memory and is noticeably faster. Use it for read-only endpoints such as lists and API responses. Skip it when you need to modify and save the document, or depend on virtuals and getters unless you add a lean plugin.
31

Tell me about a time you received critical feedback on your UI code and how you responded.

Save to ▾
Show answer
Situation: in my internship, a senior reviewer rejected my pull request because my components were large and repeated logic. Task: fix it without missing the sprint deadline. Action: I asked for examples, split the page into smaller components, extracted a custom hook for the shared fetching logic and added prop types. Result: the PR was approved the next day, and the reviewer used my hook in another feature.
32

Duplicate user accounts with the same email are being created even though the code checks for an existing email first. Why, and how do you fix it?

Save to ▾
Show answer
Check-then-insert is a race condition: two concurrent requests both see no user and both insert. The real fix is a unique index on email, normalised to lowercase, so the database rejects the second insert with error code 11000. Catch that error and return 409 Conflict. Clean up existing duplicates before building the index, otherwise index creation fails.
33

What are the core principles of a RESTful API, and which HTTP methods are idempotent?

Save to ▾
Show answer
REST models data as resources identified by URLs, uses standard HTTP methods, is stateless, and returns representations like JSON with proper status codes. Use nouns, for example GET /orders and POST /orders. GET, PUT, DELETE, HEAD and OPTIONS are idempotent: repeating them gives the same server state. POST is not idempotent, and PATCH usually is not, which matters when clients retry requests.
34

What are streams in Node.js and what types exist?

Save to ▾
Show answer
Streams process data in chunks instead of loading it all into memory. The four types are Readable (file read, HTTP request), Writable (file write, HTTP response), Duplex (TCP socket) and Transform (gzip, encryption), which modifies data as it passes. Streams handle backpressure, pausing the source when the destination is slow. pipeline() from node:stream/promises connects them safely and handles errors and cleanup.
35

How do you implement graceful shutdown for a Node.js API during deployments?

Save to ▾
Show answer
Listen for SIGTERM and SIGINT. When received, stop accepting new connections with server.close(), let in-flight requests finish, close database connections with mongoose.connection.close() and other resources, then exit with code 0. Set a timeout, for example 10 seconds, after which you force exit. In Kubernetes or behind a load balancer, also fail the readiness check first so traffic stops reaching the instance.
36

Write a deep clone function that handles nested objects, arrays and dates.

Save to ▾
Show answer
In production prefer structuredClone, but interviewers often ask for a manual version. function deepClone(value, seen = new WeakMap()) { if (value === null || typeof value !== 'object') return value; if (value instanceof Date) return new Date(value); if (seen.has(value)) return seen.get(value); const copy = Array.isArray(value) ? [] : {}; seen.set(value, copy); for (const key of Object.keys(value)) copy[key] = deepClone(value[key], seen); return copy; } The WeakMap prevents infinite loops on circular references.

Companies with offices in Pune (10)

Frequently asked questions

Which companies hire MERN Stack professionals in Pune?

Companies with large offices in Pune include TCS, Infosys, Wipro, Accenture, Cognizant, Capgemini, Tech Mahindra, LTIMindtree, Persistent Systems, EPAM Systems. Use their company pages below to practise employer-specific sets.

Are MERN Stack interviews in Pune different from other cities?

The questions depend more on the company than the city. Pune's mix of employers decides the style: It has a large mid-level job market for data and QA roles, and interviews are often practical and project-based

How do I find MERN Stack jobs in Pune?

Shortlist companies with Pune offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Pune filter, and practise the questions on this page before each interview.