Skip to content

MERN Stack Interview Questions in Noida

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

MERN Stack jobs in Noida

Noida is a major IT and IT-services hub in Delhi NCR with large campuses of service companies, product firms and fast-growing start-ups along the Noida–Greater Noida Expressway. Freshers often find their first role here, and many teams run hybrid work.

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

Solved for NoidaStart 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

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.
02

Fetch a list of users from an API inside useEffect with proper cleanup.

Save to ▾
Show answer
AbortController cancels the request if the component unmounts. function Users() { const [users, setUsers] = useState([]); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); fetch('/api/users', { signal: controller.signal }) .then((r) => r.json()) .then(setUsers) .catch((e) => { if (e.name !== 'AbortError') setError(e); }); return () => controller.abort(); }, []); if (error) return <p>Failed to load</p>; return <ul>{users.map((u) => <li key={u._id}>{u.name}</li>)}</ul>; }
03

Set a refresh token in a secure httpOnly cookie after login.

Save to ▾
Show answer
Cookie flags carry most of the security. const refreshToken = jwt.sign({ sub: user.id }, process.env.REFRESH_SECRET, { expiresIn: '7d' }); const accessToken = jwt.sign({ sub: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '15m' }); res.cookie('refreshToken', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict', path: '/api/auth/refresh', maxAge: 7 * 24 * 60 * 60 * 1000 }); res.json({ accessToken }); Read it later with the cookie-parser middleware via req.cookies.refreshToken.
04

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.
05

Tell me about a time you found and fixed a security issue in an application.

Save to ▾
Show answer
Situation: while testing an order history feature, I noticed changing the order id in the URL showed another user's order. Task: fix this insecure direct object reference before release. Action: I added an ownership check in the service layer so queries always filter by the logged-in user's id, wrote tests for cross-user access, and reviewed similar endpoints. Result: we fixed four endpoints and added ownership checks to our review checklist.
06

What is the difference between package.json and package-lock.json, and what do ^ and ~ mean?

Save to ▾
Show answer
package.json lists dependencies with version ranges, scripts and metadata. package-lock.json records the exact installed versions of every package, including nested ones, so every machine and CI build gets the same tree. Commit both and use npm ci in pipelines. A caret like ^4.18.2 allows minor and patch updates below 5.0.0; a tilde like ~4.18.2 allows only patch updates below 4.19.0.
07

Implement page-based pagination for a products API with Mongoose.

Save to ▾
Show answer
Return items plus metadata. async function listProducts(req, res) { const page = Math.max(1, Number(req.query.page) || 1); const limit = Math.min(50, Number(req.query.limit) || 10); const [items, total] = await Promise.all([ Product.find().sort({ createdAt: -1 }) .skip((page - 1) * limit).limit(limit).lean(), Product.countDocuments() ]); res.json({ items, page, totalPages: Math.ceil(total / limit) }); } Capping limit prevents clients from requesting huge pages.
08

What are BSON and ObjectId in MongoDB?

Save to ▾
Show answer
BSON is the binary format MongoDB uses to store documents. It extends JSON with types like Date, ObjectId, Decimal128, binary data and 32 or 64-bit integers, and is fast to traverse. ObjectId is the default 12-byte _id value made of a 4-byte timestamp, a 5-byte random value and a 3-byte counter. Because it starts with a timestamp, ObjectIds roughly sort by creation time.
09

Which HTTP status codes should a REST API commonly return?

Save to ▾
Show answer
Use 200 OK for successful reads and updates, 201 Created after a POST that creates a resource, and 204 No Content for successful deletes. Use 400 for invalid input, 401 when authentication is missing or invalid, 403 when the user is authenticated but not allowed, 404 for missing resources, 409 for conflicts such as duplicate email, 422 for validation errors, 429 for rate limits and 500 for unexpected server errors.
10

Design a payment endpoint so that client retries never charge a user twice.

Save to ▾
Show answer
Make the endpoint idempotent with an idempotency key. The client generates a unique key per checkout and sends it in a header. The server stores the key with a unique index along with the request hash and the result. If the same key arrives again, return the stored response instead of reprocessing. Use a status field for in-progress requests and verify final status through the payment gateway webhook.
11

Your script crashes with out of memory while reading a 5 GB log file. How would you rewrite it?

Save to ▾
Show answer
fs.readFile loads the whole file into memory, which exceeds the heap. Use a stream instead: fs.createReadStream with readline lets you process one line at a time with for await, keeping memory flat. If you need to transform and write output, connect read, transform and write streams with pipeline so backpressure and errors are handled. Increasing --max-old-space-size only hides the real problem.
12

Your MERN product is expected to grow from 1,000 to 1 lakh daily users. How would you prepare the architecture?

Save to ▾
Show answer
Make the API stateless and run multiple instances behind a load balancer with autoscaling. Serve the React build and media from a CDN. Move sessions, rate limits and caches to Redis. Optimise MongoDB with proper indexes, a replica set, read preferences for analytics and plan sharding if data grows. Push slow work to queues, add monitoring and alerts, and load test before launch to find limits.
13

Describe a production issue you handled in a Node.js service.

Save to ▾
Show answer
Situation: our order API started timing out every evening at peak. Task: as the on-call developer I had to restore it. Action: I checked logs and metrics, found event-loop lag spikes, and traced them to a synchronous CSV export running inside a request. I moved the export to a background job and added event-loop lag alerts. Result: p95 latency dropped from 4 seconds to 300 ms and timeouts stopped.
14

Explain hoisting in JavaScript with an example.

Save to ▾
Show answer
Hoisting means declarations are processed before code runs. Function declarations are hoisted fully, so you can call them before they appear. var declarations are hoisted but initialised to undefined, so console.log(x) before var x = 5 prints undefined. let, const and class declarations are hoisted too, but accessing them before the declaration throws a ReferenceError because of the temporal dead zone. Function expressions assigned to variables follow the variable rules.
15

What are React fragments and portals?

Save to ▾
Show answer
A fragment, written <>...</> or <Fragment key={id}>, groups children without adding an extra DOM element, which keeps tables and flex layouts valid. A portal, created with createPortal(child, domNode), renders children into a different DOM node such as document.body while keeping them in the same React tree, so context and event bubbling still work. Portals are used for modals, tooltips and toasts that must escape overflow hidden containers.
16

How do you implement code splitting in a React app?

Save to ▾
Show answer
Use dynamic import with React.lazy, for example const Admin = lazy(() => import('./Admin')), and wrap it in a Suspense boundary with a fallback. Bundlers like Vite then create a separate chunk that loads only when needed. Split by route first, then by heavy components like charts, editors and maps. Preload likely next routes on hover, and check results with a bundle analyser such as rollup-plugin-visualizer.
17

Write a Supertest integration test for a POST /api/users endpoint.

Save to ▾
Show answer
Import the app, not the running server. import request from 'supertest'; import app from '../src/app.js'; describe('POST /api/users', () => { it('creates a user', async () => { const res = await request(app) .post('/api/users') .send({ name: 'Aman', email: 'aman@test.com' }) .expect(201); expect(res.body.email).toBe('aman@test.com'); }); it('rejects invalid email', async () => { await request(app).post('/api/users').send({ name: 'A', email: 'x' }).expect(400); }); }); Connect to mongodb-memory-server in a beforeAll hook.
18

How do transactions work in MongoDB and when do you need them?

Save to ▾
Show answer
Single-document writes are already atomic, so good embedded design avoids most transactions. Multi-document ACID transactions are available on replica sets and sharded clusters, not on a standalone server. In Mongoose, start a session, call session.withTransaction() and pass the session to every operation. Use them for cases like transferring wallet balance between two users. They add latency and should stay short, ideally under one second.
19

The business wants total sales per category for the last 30 days. How would you build it in MongoDB?

Save to ▾
Show answer
Use an aggregation pipeline: $match orders with status paid and createdAt in the last 30 days, using an index on createdAt; $unwind the items array; $group by items.category summing items.price times items.qty; then $sort by total descending. If the report is viewed often, precompute daily totals into a summary collection with a scheduled job or $merge, so the dashboard reads small documents.
20

What is NoSQL injection and how do you prevent it in a MongoDB app?

Save to ▾
Show answer
NoSQL injection happens when user input is placed directly into a query and contains operators. For example, a login body of { email: 'a@b.com', password: { $ne: null } } could match any password if passed straight to findOne. Prevent it by validating types with zod or Joi, casting inputs to strings, stripping keys starting with $ or containing dots, enabling Mongoose strictQuery, and never building $where queries from user input.
21

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.
22

Build a simple todo list in React with add and delete.

Save to ▾
Show answer
Update arrays immutably. function Todos() { const [todos, setTodos] = useState([]); const [text, setText] = useState(''); const add = (e) => { e.preventDefault(); if (!text.trim()) return; setTodos((t) => [...t, { id: crypto.randomUUID(), text }]); setText(''); }; const remove = (id) => setTodos((t) => t.filter((x) => x.id !== id)); return ( <form onSubmit={add}> <input value={text} onChange={(e) => setText(e.target.value)} /> <ul>{todos.map((t) => ( <li key={t.id}>{t.text} <button type='button' onClick={() => remove(t.id)}>x</button></li> ))}</ul> </form> ); }
23

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.
24

Your Node.js API runs on an 8-core server but CPU monitoring shows only one core busy. What do you do?

Save to ▾
Show answer
A Node process runs JavaScript on a single thread, so one instance uses about one core. Run multiple instances: PM2 in cluster mode with -i max, the cluster module, or several containers behind a load balancer such as Nginx. Because instances do not share memory, move sessions, caches and rate-limit counters to Redis, and make sure the app is stateless so any instance can serve any request.
25

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.
26

Explain destructuring, the spread operator and rest parameters.

Save to ▾
Show answer
Destructuring unpacks values from arrays or objects into variables, for example const { name, email } = user, with optional defaults and renaming. Spread (...) expands an iterable or object, used to copy arrays, merge objects or pass arguments. Rest uses the same syntax to collect remaining items, as in function sum(...nums) or const { password, ...safeUser } = user. In React, spread is used constantly to create new state objects immutably.
27

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.
28

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
29

What is the difference between props and state in React?

Save to ▾
Show answer
Props are inputs passed from a parent to a child component; they are read-only inside the child. State is data owned and managed by a component itself, created with useState or useReducer, and changing it triggers a re-render. A common pattern is that a parent keeps state and passes both the value and a setter function down as props to children.
30

Write a useDebounce hook and use it for a search input.

Save to ▾
Show answer
The hook returns a value that updates only after a delay. function useDebounce(value, delay = 400) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]); return debounced; } function Search() { const [q, setQ] = useState(''); const term = useDebounce(q); const { data } = useFetch(`/api/products?search=${encodeURIComponent(term)}`); return <input value={q} onChange={(e) => setQ(e.target.value)} />; }
31

Create a compound index for a user's order history query and verify it is used.

Save to ▾
Show answer
Query: orders of one user, newest first. db.orders.createIndex({ userId: 1, createdAt: -1 }) db.orders.find({ userId: ObjectId('...') }) .sort({ createdAt: -1 }) .limit(20) .explain('executionStats') Check that the winning plan shows IXSCAN, not COLLSCAN, and that totalDocsExamined is close to nReturned. In Mongoose, declare it with orderSchema.index({ userId: 1, createdAt: -1 }).
32

Tell me about a time you improved the performance of a slow database-driven feature.

Save to ▾
Show answer
Situation: our admin orders page took 8 seconds to load. Task: I was asked to fix it within a sprint. Action: I profiled the API, found a populate on every row plus an unindexed sort, added a compound index, replaced populate with a single $lookup projecting only needed fields, and used lean. Result: load time dropped below 600 ms and I shared an indexing checklist with the team.
33

How have you helped junior developers improve their React skills?

Save to ▾
Show answer
Situation: two freshers joined my team and their PRs had repeated effect bugs. Task: help them ramp up without slowing the sprint. Action: I ran short weekly sessions on effects, keys and state structure, paired with them on real tickets, and wrote a review checklist. I gave specific, kind comments in reviews. Result: within two months their PRs needed far fewer changes, and one of them now runs the sessions.
34

Your API becomes unresponsive whenever a user uploads an image for resizing. What is happening and how do you fix it?

Save to ▾
Show answer
Resizing is CPU-bound work running on the main thread, so it blocks the event loop and every other request waits. Fix it by moving the work off the main thread: use a worker_threads pool, a native library like sharp that works in the libuv pool, or better, push a job to a queue such as BullMQ with Redis and process it in a separate worker service, then notify the client.
35

Implement a shopping cart with useReducer.

Save to ▾
Show answer
A pure reducer keeps cart logic in one place. function cartReducer(state, action) { switch (action.type) { case 'add': { const found = state.find((i) => i.id === action.item.id); return found ? state.map((i) => i.id === action.item.id ? { ...i, qty: i.qty + 1 } : i) : [...state, { ...action.item, qty: 1 }]; } case 'remove': return state.filter((i) => i.id !== action.id); case 'clear': return []; default: return state; } } const [cart, dispatch] = useReducer(cartReducer, []); dispatch({ type: 'add', item: product });
36

A component calls setState inside useEffect and the app goes into an infinite render loop. Why?

Save to ▾
Show answer
The effect updates state, which re-renders, which runs the effect again. This happens when the dependency array is missing, or when a dependency is a new object or array created every render, or when the effect sets the same state it depends on. Add correct dependencies, move object creation inside the effect or memoize it, and ask whether the value can be calculated during render instead.

Companies with offices in Noida (6)

Frequently asked questions

Which companies hire MERN Stack professionals in Noida?

Companies with large offices in Noida include HCLTech, Tech Mahindra, Publicis Sapient, GlobalLogic, Happiest Minds Technologies, Paytm. Use their company pages below to practise employer-specific sets.

Are MERN Stack interviews in Noida different from other cities?

The questions depend more on the company than the city. Noida's mix of employers decides the style: Freshers often find their first role here, and many teams run hybrid work

How do I find MERN Stack jobs in Noida?

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