CoreHRx Jobs

Apply in one click, save jobs and take free mock tests.

Register free Log in
Hiring? Post jobs with CoreHRx
My account
user

View & update profile
Interview guide

MERN Stack Interview Questions and Answers: 60 Questions from Easy to Hard

This guide is for freshers and working developers in India preparing for MERN stack roles at product startups, IT services companies and agencies that build web apps with MongoDB, Express, React and Node.js. It focuses on how the parts work together: the path of a request from a React screen through Express to MongoDB and back, Mongoose, login with cookies and tokens, Redux, aggregation for dashboards, errors, security and deployment. For depth on one part alone, see our React, Node.js and MongoDB interview guides. The 60 questions come in three levels, and every code snippet was run on current versions. Answer each question aloud first, then compare, and take the MERN Stack Developer mock test to practise under time.

  • 60 questions, 3 levels
  • Updated
  • CoreHRx Jobs

What MERN stack interviews cover

  • How the four parts work together: React calling Express, Express calling MongoDB through Mongoose, and what the JSON looks like at each step.
  • A project round, often the longest: your own MERN project's data model, login, hardest bug and deployment, with follow-up questions that check you built it yourself.
  • Authentication and security: JWT or sessions, cookies versus localStorage, role checks, CORS, input validation and holes such as mass assignment.
  • State management with Redux Toolkit or a server-cache library, plus data features such as filters, pagination and dashboards built with aggregation.
  • At many companies, a timed hands-on task: a small CRUD app with login, or a React screen that reads data from an API.

How freshers should prepare

  • Build one complete MERN project yourself, such as a job board or an expense tracker, with signup, login, roles, a filtered list with pagination, and deploy it so you can share the link.
  • Practise drawing the request path for one feature, from the click in React to the document in MongoDB and back, and explain every status code your API returns.
  • Learn each layer from our React, Node.js and MongoDB guides first, then practise the joining points on this page: CORS, JSON bodies, error responses and login.
  • Rehearse a timed task: an Express and Mongoose CRUD API plus a React page that uses it, with a short README that says how to run it.

How experienced candidates should prepare

  • Prepare two or three production stories: a slow page you measured and fixed, a security issue you found, and a release that went wrong, each with what you changed afterwards.
  • Be ready to defend design choices: Mongoose or the plain driver, cookies or tokens, Redux Toolkit or TanStack Query, populate or copied fields, and what each one costs.
  • Revise recent changes: Express 5 path syntax, async errors and query parsing, Mongoose 9 middleware without next(), React 19 features, and the Node.js LTS line you run.
  • Expect design rounds on a whole MERN product: running on several servers, caching, background jobs, file storage, and how you would split the work across a team.

Versions to know

  • React 19 is the current major (19.3 was released in September 2026), Express 5 is the default version on npm, and Mongoose 9 has been the current major since November 2025.
  • Node.js 26 has been the Active LTS line since October 2026, Node.js 24 and 22 are in Maintenance LTS (22 until April 2027), and Node.js 20 has reached end of life.
  • MongoDB 9.0 became the current stable server release in September 2026; ask which version your target employer runs and read its release notes before the interview.

Common mistakes to avoid

  • Treating a check in React as security: hiding a button or a route does not stop anyone from calling the API, so every rule must also live in Express.
  • Answering for one layer only: when asked why a page is slow or broken, say how you would check React, the network, Express and MongoDB in turn.
  • Sending raw Mongoose errors, stack traces or password hashes to the browser, or saving req.body straight into a model.
  • Using outdated syntax without saying so: Mongoose callbacks, next() in Mongoose 9 pre hooks, a bare asterisk route in Express 5, or createStore instead of Redux Toolkit.
  • Listing tools you cannot explain: if your resume says JWT, Redux or aggregation, expect detailed questions about that code in your project.

MERN Stack interview questions: Easy questions (freshers)

20 questions

1. What is the MERN stack, and what does each of its four parts do in one application?

MERN is MongoDB, Express, React and Node.js, a stack where one team writes JavaScript, or TypeScript, for every layer. In a job portal, React runs in the browser and draws the screens, such as the job list and the apply form. Node.js runs the server code, and Express, the framework on top of it, defines routes such as GET /api/jobs, runs middleware and sends JSON back. MongoDB stores documents in collections such as users, jobs and applications, usually through Mongoose. React and Express talk through HTTP and JSON, while Express reaches MongoDB through the driver's own protocol. A strong answer adds what MERN does not give you: login, validation, security and deployment.

2. Trace one Apply click through a MERN app and say what form the data takes at each step.

In React it is a JavaScript object in state, such as a jobId and a cover note. fetch sends it as a JSON string with Content-Type application/json. express.json parses it back into a plain object on req.body, where every id is still just a string. The route passes the fields to a Mongoose model, which casts them to the schema types, so jobId becomes an ObjectId and the default status and timestamps are added, and the driver encodes the document as BSON for MongoDB. On the way back res.json calls toJSON, ObjectIds and dates become strings again, and React stores them in state. Each conversion is a place where bugs hide.

3. Why should a React app never connect to MongoDB directly, even though the MongoDB driver is also JavaScript?

It could not even run there: the Node.js driver speaks MongoDB's wire protocol over raw TCP sockets, and browsers give web pages no raw sockets, only HTTP-based APIs and WebSocket. More importantly, everything shipped to the browser can be read by the user, so a connection string inside the bundle would give anyone full access to the database. MongoDB also cannot decide who may read which record; that logic belongs in Express, which checks the logged-in user, validates input, applies rules such as one application per job, and returns only the fields a screen needs. On Atlas or your own servers, accept connections only from the API servers.

4. What is the difference between a schema, a model and a document in Mongoose?

A schema describes the shape of a document: field types, required fields, defaults, enums, limits and options such as timestamps. A model is compiled from a schema with mongoose.model and is the class you query with, linked to one collection, so the Job model maps to the jobs collection. A document is one instance of the model, one job, with methods such as save and validate. In the snippet the schema trims the title and fills in the default status, and validation rejects the negative salary before anything reaches MongoDB. Mongoose 9.12, used here, marks validateSync as deprecated, so use await doc.validate(). These rules apply only to writes made through Mongoose.

Example
const mongoose = require('mongoose');
const jobSchema = new mongoose.Schema({
  title: { type: String, required: true, trim: true },
  status: { type: String, enum: ['open', 'closed'], default: 'open' },
  salaryMax: { type: Number, min: 0 },
}, { timestamps: true });
const Job = mongoose.model('Job', jobSchema);       // model = class for the jobs collection
const doc = new Job({ title: '  MERN Developer ', salaryMax: -1 }); // document
console.log(doc.title, doc.status); // MERN Developer open
doc.validate().catch((err) => console.log(err.errors.salaryMax.message));
// Path `salaryMax` (-1) is less than minimum allowed value (0).

5. Why do many MERN teams use Mongoose instead of only the official MongoDB driver, and what does it cost?

MongoDB accepts any document shape, so Mongoose adds a schema in the application: it casts types (the string "25" becomes the number 25 for a Number field), validates required fields and enums, fills defaults and timestamps, and gives you middleware hooks, populate for references and a tidy model API. That consistency helps when several developers write to the same collections. The cost is an extra layer: Mongoose documents are heavier than plain objects, and some defaults surprise people, such as strict mode dropping unknown fields or update validators being off. Mongoose uses the official driver underneath, and Model.collection exposes the underlying collection when a hot path needs it.

6. Which collections would you create for a simple job portal, and how would you link them?

I would start with users (candidates and employers, with a role field), companies, jobs and applications. A job stores companyId and postedBy as ObjectId references and copies the few company fields every list shows, the name and logo, so the job list needs no join. Applications get their own collection with jobId and candidateId, because one popular job in Bengaluru can receive thousands of applications and an array inside the job document would keep growing. A unique compound index on jobId and candidateId stops double applications. The interviewer checks that you design from the screens and their queries, not from the tables you would draw for SQL.

7. Why does an _id or a date from MongoDB arrive in React as a plain string, and how do you show that date in Indian time?

JSON has no ObjectId or Date type. When Express calls res.json, an ObjectId becomes its 24-character hex string and a Date becomes an ISO string in UTC, as the snippet shows. React therefore compares ids as strings and must turn dates back into Date objects before formatting them. Format in the user's time zone only at display time, here Asia/Kolkata with the en-IN locale, which turns 20:15 UTC on 18 November into 1:45 am on 19 November. Keep storing UTC in MongoDB. A common bug is slicing the ISO string to get the date, which shows the previous day for anything posted between midnight and 5:30 am IST.

Example
const mongoose = require('mongoose');
const job = { _id: new mongoose.Types.ObjectId('6919a3c0f1e2d3c4b5a69788'),
  postedAt: new Date('2026-11-18T20:15:00Z') };
const body = JSON.parse(JSON.stringify(job)); // what React receives
console.log(typeof body._id, body.postedAt); // string 2026-11-18T20:15:00.000Z
const ist = new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium',
  timeStyle: 'short', timeZone: 'Asia/Kolkata' });
console.log(ist.format(new Date(body.postedAt))); // 19 Nov 2026, 1:45 am

8. In what order does Express run middleware, and why is req.body undefined in some routes?

Express runs middleware and routes in the order you register them, and each one either ends the response or calls next. A JSON parser registered after a route has not run when that route executes. In Express 5, req.body is undefined when no parser has handled the body; Express 4 gave an empty object. In the snippet, the route registered before express.json sees undefined, while the route after it receives the parsed body. So put the JSON parser, cookie parsing and CORS near the top, then the routes, then a 404 handler, and the error handler last. React must also send Content-Type application/json, or the parser skips the body.

Example
const express = require('express');
const request = require('supertest');
const app = express();
app.post('/early', (req, res) => res.json({ body: req.body ?? 'undefined' }));
app.use(express.json());
app.post('/late', (req, res) => res.json({ body: req.body }));
(async () => {
  console.log((await request(app).post('/early').send({ t: 'Dev' })).body); // { body: 'undefined' }
  console.log((await request(app).post('/late').send({ t: 'Dev' })).body);  // { body: { t: 'Dev' } }
})();

9. React runs on the Vite dev server at port 5173 and calls Express on port 5000. Do you fix the CORS error with the cors package or with the Vite proxy, and what changes in production?

Both work, for different reasons. A Vite proxy, set under server.proxy for paths starting with /api, makes the browser talk only to port 5173 while Vite forwards the call to Express, so there is no cross-origin request, no CORS headers to maintain, and cookies behave as they will in production. The cors package instead makes Express answer with Access-Control-Allow-Origin for an exact origin you list, which you need when the front end really lives on another domain. Avoid reflecting every origin back with credentials allowed, which lets any website read logged-in responses. In production, serving the React build and the API from one domain usually makes CORS unnecessary.

10. How should the React app send a new job to the API, and what should the API send back?

React sends POST /api/jobs with Content-Type application/json and a body holding only the form fields, such as title, city, salaryMin, salaryMax and skills. It never sends postedBy or status, because the server sets those from the logged-in user and its own rules. Express validates the input, saves it and replies 201 Created with the saved job, including its _id and timestamps, so React can open the new job's page without another request. Validation problems get 400 with a message per field, a missing login gets 401, and a candidate trying to post gets 403. Keep one error shape for every endpoint, so the front end can handle errors in one place.

11. A component must show jobs from GET /api/jobs. Which states should it handle, and how?

Four states: loading, error, empty and success. Keep them explicit, for example status, data and error in state, or use a data library such as TanStack Query or RTK Query, which tracks them for you. While loading, show a skeleton instead of a blank page. On error, show a short message with a Retry button instead of a broken screen. If the API returns an empty array, say that no jobs match these filters and offer to clear them, because an empty list is not an error. Only the success state maps over the jobs, with each key set to the job's _id. Many candidates handle only the success state.

12. In a React Router app, how does the job details page at /jobs/:id get its data from Express, and how do you send the user there after creating a job?

The route is declared as jobs/:id, and the page component reads id with useParams, always as a string. It then requests GET /api/jobs/ plus that id, with the id in the effect's dependency list or in the query key of TanStack Query or RTK Query, because React Router reuses the same component when the user moves from one job to another. A 404 or a malformed id shows a not-found message, not a crash. After the create form gets 201 with the new job, call navigate from useNavigate with the new job's path, often with replace so Back does not reopen the form. Use Link, not a plain anchor, so the page does not fully reload.

13. Why are Express handlers that use Mongoose usually async functions, and what happens if you forget an await?

Every Mongoose call goes to the database over the network and returns a Query or a promise, which the handler awaits without blocking other requests. Forget the await and you hold the Query object instead of the user. As the snippet shows, that object is always truthy, so a check like if (!user) return 404 never fires, and passing it to res.json throws a TypeError about a circular structure, which becomes a 500. A forgotten await before save is worse: the reply says success, then the failed write becomes an unhandled rejection, which since Node.js 15 crashes the whole process. Express 5 passes rejected promises to the error handler only when you await or return them.

Example
const mongoose = require('mongoose');
const User = mongoose.model('User', new mongoose.Schema({ email: String }));
const user = User.findOne({ email: 'nobody@example.com' }); // await forgotten
console.log(user.constructor.name, Boolean(user)); // Query true
try { JSON.stringify(user); } catch (e) { console.log(e.name); } // what res.json(user) hits: TypeError

14. What does an auth middleware in Express do, and how do the routes after it know who the user is?

It runs before the protected routes and answers one question: who sent this request? It reads the token from the httpOnly cookie or the Authorization header, verifies the signature and expiry, for example with jsonwebtoken's verify and a fixed list of allowed algorithms, and on success sets req.user to a small object such as id, role and companyId, then calls next. A missing or invalid token gets 401 and the chain stops. Later routes read req.user instead of trusting any id in the body. That is the line between authentication and authorisation: the middleware proves identity, and each route still checks role and ownership before acting.

15. How do you store passwords in a MERN app, and how do you make sure the hash never reaches React?

Never store the password itself. Hash it with a slow, salted algorithm: the OWASP password storage guidance prefers Argon2id and accepts bcrypt with a work factor of at least 10, remembering that bcrypt uses only the first 72 bytes. Hash on the server, in the signup route or a Mongoose pre save hook, which in Mongoose 9 is an async function without next. Then keep the hash inside the server: select: false leaves it out of normal queries, and a toJSON transform removes it and __v whenever a document goes through res.json, as the snippet shows. The login route asks for it explicitly with select('+passwordHash').

Example
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  email: { type: String, required: true, lowercase: true },
  passwordHash: { type: String, required: true, select: false },
}, { toJSON: { transform(doc, ret) { delete ret.passwordHash; delete ret.__v; return ret; } } });
const User = mongoose.model('User', userSchema);
const u = new User({ email: 'Asha@Example.com', passwordHash: '$2b$12$examplehash' });
console.log(JSON.parse(JSON.stringify(u))); // no passwordHash in the API reply

16. What problem does Redux solve, and what are the store, an action and a reducer?

Redux keeps shared state in one store outside the component tree, so distant components, such as a job card and a header badge, read and change the same data without passing props through many levels. An action is a plain object that describes what happened, like the toggle action in the snippet with its type and payload. A reducer is a pure function that takes the current state and an action and returns the next state. The Redux team calls Redux Toolkit the officially recommended way to write Redux: createSlice generates the actions and lets you write mutating-style code that Immer turns into immutable updates, and configureStore sets up the store and DevTools.

Example
const { configureStore, createSlice } = require('@reduxjs/toolkit');
const savedJobs = createSlice({
  name: 'savedJobs',
  initialState: { ids: [] },
  reducers: {
    toggle(state, action) {
      const i = state.ids.indexOf(action.payload);
      if (i === -1) state.ids.push(action.payload); else state.ids.splice(i, 1);
    },
  },
});
const store = configureStore({ reducer: { savedJobs: savedJobs.reducer } });
store.dispatch(savedJobs.actions.toggle('J101'));
console.log(savedJobs.actions.toggle('J7')); // { type: 'savedJobs/toggle', payload: 'J7' }
console.log(store.getState()); // { savedJobs: { ids: [ 'J101' ] } }

17. In a MERN job portal, which data would you keep in Redux, which in local component state, and which in a server-cache library?

Redux suits data that several unrelated parts of the app need, or that must survive navigation: the logged-in user and role, the saved-jobs list shown on many pages, or a multi-step application draft. Local state suits what one component owns: the text in a search box while typing, whether a modal is open, which tab is selected. Data that comes from the API is a third kind, server state, which needs caching, refetching and handling of stale data, and RTK Query or TanStack Query do that better than hand-written reducers. Putting every input into Redux makes the app slower and the code harder to follow, and interviewers listen for this judgement.

18. Why does fetch not throw an error on a 404 or 500 response, and how should you handle it?

The fetch promise rejects only when the request itself fails, for example a network error, a response blocked by CORS or a malformed URL. Any HTTP reply, even 404 or 500, is a successful fetch: res.ok is false and res.status holds the code, as in the snippet. A common MERN bug is calling res.json and rendering the error body as if it were data. Write one small wrapper for every call that checks res.ok, reads the JSON error body and throws an error carrying the status and the server's message, so components and Redux thunks deal with one kind of failure. Axios, by contrast, rejects on non-2xx codes by default.

Example
const express = require('express');
const app = express();
app.get('/api/jobs/:id', (req, res) => res.status(404).json({ error: 'Job not found' }));
const server = app.listen(0, '127.0.0.1', async () => {
  const res = await fetch(`http://127.0.0.1:${server.address().port}/api/jobs/42`);
  console.log(res.ok, res.status); // false 404, and no exception was thrown
  if (!res.ok) console.log((await res.json()).error); // Job not found
  server.close();
});

19. An employer dashboard shows how many applications are in each status. Why count them in MongoDB with an aggregation instead of in React?

Sending every application to the browser just to count it wastes bandwidth and memory, exposes candidate details the screen does not need, and gets slower as the job gets popular. An aggregation counts where the data lives: $group by status with a $sum of 1 returns a few small rows, as in the snippet, which gives applied 3, rejected 1 and shortlisted 1. In the real route, start with a $match on the employer id taken from req.user, so one company never counts another's applications and an index can be used. React then just maps the rows into a chart. Statuses with no applications do not appear, so fill them with zero.

Example
const { aggregate } = require('mingo');
const applications = [
  { jobId: 'J1', status: 'applied' }, { jobId: 'J1', status: 'shortlisted' },
  { jobId: 'J2', status: 'applied' }, { jobId: 'J2', status: 'rejected' },
  { jobId: 'J2', status: 'applied' },
];
console.log(aggregate(applications, [
  { $group: { _id: '$status', count: { $sum: 1 } } },
  { $sort: { count: -1, _id: 1 } },
])); // applied 3, rejected 1, shortlisted 1

20. What are the main pieces you need to deploy a MERN app to production?

First, the React build: npm run build creates static HTML, JavaScript and CSS files that Nginx, a CDN or Express itself can serve. Second, the Node.js API on an LTS release such as Node.js 24 or 26, kept running by PM2, systemd or a Docker container, so it restarts after a crash or a reboot. Third, a MongoDB deployment, such as an Atlas cluster or a self-managed replica set, that accepts connections only from the API servers. Fourth, a reverse proxy with HTTPS in front of Node, and environment variables for secrets such as the database URI and the JWT secret. Finally, logs, backups and a health-check URL.

Ready to check yourself? Take the free MERN Stack mock test

MERN Stack interview questions: Medium questions (1-3 years)

20 questions

21. The React app on app.example.in logs in through an Express API on api.example.in, but the login cookie is never sent on later calls. What must be set on both sides?

Both sides must opt in. In React, every fetch, including the login call, needs credentials set to include, because cross-origin requests leave cookies out by default. On the API, the CORS reply must carry Access-Control-Allow-Credentials: true and the exact origin, never a wildcard, or the browser refuses the response. The cookie itself should be httpOnly and Secure with SameSite set to Lax; that works here because subdomains of one registered domain count as the same site, while two unrelated domains would block a Lax cookie on fetch calls. An httpOnly cookie beats localStorage because injected scripts cannot read it, but it then needs CSRF protection.

22. After a page refresh, the React app forgets who is logged in and briefly shows the login page. How do you restore the session cleanly?

The httpOnly cookie survives the refresh, but React state does not, so on startup an AuthProvider calls GET /api/auth/me with credentials included. Its state starts as checking, then becomes the user object, or null when the API replies 401. While it is checking, protected routes render a spinner instead of redirecting, which removes the flash of the login page. Keep the user in context or Redux, and treat a 401 from any later call as a logout. Do not decide what a user may see from a role copied into localStorage; it is only a cache, and the API checks every request again anyway.

23. How do you allow only employers to post jobs, both in React Router and in Express?

In React, wrap the employer pages in a guard component that reads the user from the auth context and redirects candidates to their own dashboard, and hide the Post a job button for them. That is only for usability. The real rule lives in Express: an auth middleware sets req.user from the cookie or token, and a requireRole middleware like the one in the snippet returns 401 when nobody is logged in and 403 when the role is wrong. Each route lists its guards in order, and the run gave 401, 403 and 201 for the three cases. For editing, add an ownership check, because a role check alone lets any employer edit another company's job.

Example
const requireRole = (...roles) => (req, res, next) => {
  if (!req.user) return res.status(401).json({ error: 'Login required' });
  if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'Not allowed' });
  next();
};
// requireAuth checks the cookie or token and sets req.user (or null)
app.post('/api/jobs', requireAuth, requireRole('employer', 'admin'), createJob);
app.patch('/api/jobs/:id', requireAuth, requireRole('employer'), updateJob);
// no login: 401, candidate: 403, employer: 201

24. findByIdAndUpdate saved a negative salary and skipped the password-hashing hook. Why, and how do you fix it?

Two Mongoose defaults cause this. Update validators are off by default, so findByIdAndUpdate, updateOne and similar methods cast types but skip min, enum and custom validators unless you pass runValidators: true. And save middleware runs only on save: the Mongoose documentation says pre and post save hooks are not executed on findOneAndUpdate and other update methods, so a pre save hook that hashes passwords never runs, and a plain password can land in the database. Fix it by setting runValidators, per query or globally, loading the document and calling save for changes that need document hooks, or adding query middleware for findOneAndUpdate. Update only the allowed fields with $set.

25. How does populate() work, and when is an aggregation with $lookup the better choice?

populate replaces an ObjectId reference with the referenced document. Mongoose runs a separate query on the referenced collection after the main query, so it is not a database join, and a reference that points nowhere comes back as null. It is convenient for showing the company name and logo on 20 job cards: Job.find().populate('company', 'name logo') makes two queries, not 21. Choose $lookup when you must filter, sort or group on fields of the other collection, such as jobs from companies rated above 4, because populate cannot filter the main query by populated data. Always pass a field list, or whole user documents, sometimes with private fields, reach React.

26. A field sent by the React form never reaches MongoDB, and a filter with a misspelled field returns no jobs. What is Mongoose strict mode doing?

With strict on, the default, Mongoose drops any path that is not in the schema when you create or update a document, so a typo such as cty in the request, or a field added in the front end but not in the schema, silently disappears; in the snippet doc.toObject().cty is undefined. Queries follow strictQuery, which is false by default in current Mongoose, so the misspelled filter is sent as it is and matches nothing. With strictQuery set to true, Mongoose removes unknown filter keys instead, the filter becomes empty and matches every job, which is dangerous with updateMany or deleteMany. Validate request bodies against an explicit schema so typos fail loudly.

Example
const mongoose = require('mongoose');
const Job = mongoose.model('Job', new mongoose.Schema({ title: String, city: String }));
const doc = new Job({ title: 'Node Developer', cty: 'Pune' }); // typo sent by the form
console.log(doc.toObject().cty); // undefined: strict mode dropped the unknown path
const q1 = Job.find({ cty: 'Pune' }); q1.cast(Job);
console.log(q1.getFilter()); // { cty: 'Pune' } is kept, so it matches nothing
const q2 = Job.find({ cty: 'Pune' }).setOptions({ strictQuery: true }); q2.cast(Job);
console.log(q2.getFilter()); // {} : the filter is gone and every job matches

27. Every API call hangs for about 10 seconds and then fails with "buffering timed out after 10000ms". What is wrong, and how should the server start?

Mongoose buffers model calls until a connection is open. If mongoose.connect was never called, has not succeeded or points at the wrong URI, every query waits in that buffer and fails after bufferTimeoutMS, 10,000 ms by default, as in the snippet. Typical causes are a missing MONGODB_URI on the server, the server's IP missing from the Atlas IP access list, or a wrong database user. Fix the start-up order: await mongoose.connect first and only then call app.listen, log the connection error and exit with a non-zero code so PM2 or Docker restarts the process. A health-check route should report the database state, so the load balancer skips a broken instance.

Example
const mongoose = require('mongoose');
const Job = mongoose.model('Job', new mongoose.Schema({ title: String }));
// mongoose.connect() was never called or has not succeeded
Job.find().catch((e) => console.log(e.message));
// Operation `jobs.find()` buffering timed out after 10000ms

28. How do you turn Mongoose errors such as ValidationError, CastError and duplicate key errors into clear responses for React?

Register one error-handling middleware with four arguments after all routes and map known errors to stable codes. A ValidationError becomes 400 with a fields object, one message per path, which the React form shows under each input. A CastError, usually a malformed id in the URL, becomes 400 or 404 instead of a 500. A duplicate key error from a unique index has code 11000, so reply 409 and name the field, for example that the email is already registered. Everything else is logged in full on the server and returned as a generic 500, so stack traces never reach the browser. In the run, four test routes returned 400, 400, 409 and 500.

Example
const mongoose = require('mongoose');
function errorHandler(err, req, res, next) {
  if (err instanceof mongoose.Error.ValidationError) {
    const fields = Object.fromEntries(Object.entries(err.errors).map(([k, e]) => [k, e.message]));
    return res.status(400).json({ code: 'VALIDATION_FAILED', fields });
  }
  if (err instanceof mongoose.Error.CastError) return res.status(400).json({ code: 'INVALID_ID' });
  if (err.code === 11000) {
    return res.status(409).json({ code: 'DUPLICATE', fields: Object.keys(err.keyValue ?? {}) });
  }
  console.error(err); // full detail stays in the server log
  res.status(500).json({ code: 'SERVER_ERROR', message: 'Something went wrong' });
}
app.use(errorHandler); // registered after every route

29. How would you design GET /api/jobs with filters, sorting and paging so the React list page can be bookmarked and shared?

Keep every filter in the URL, such as city, mode, sort and page in the query string. React reads and updates them with useSearchParams, so refresh, the back button and shared links all work. The API never passes req.query straight to MongoDB: it builds the filter from allowed fields, maps sort names to fixed sort objects with _id as a tie-breaker so pages do not repeat items, and caps the limit. In the snippet a limit of 500 becomes 50, and a city sent as an array is ignored, which matters because Express 5 turns repeated keys such as city=Pune and city=Noida into an array. Return the items with page, limit and total.

Example
const SORTS = { newest: { createdAt: -1, _id: -1 }, salary: { salaryMax: -1, _id: -1 } };
function buildJobQuery(q) {
  const filter = { status: 'open' };
  if (typeof q.city === 'string' && q.city) filter.city = q.city; // ignores arrays and objects
  if (q.mode === 'remote' || q.mode === 'office') filter.workMode = q.mode;
  const limit = Math.min(Math.max(parseInt(q.limit, 10) || 20, 1), 50);
  const page = Math.max(parseInt(q.page, 10) || 1, 1);
  return { filter, sort: SORTS[q.sort] ?? SORTS.newest, skip: (page - 1) * limit, limit };
}
console.log(buildJobQuery({ city: 'Pune', mode: 'remote', sort: 'salary', page: '3', limit: '500' }));
console.log(buildJobQuery({ city: ['Pune', 'Noida'], sort: 'title', page: '-2' }));

30. How do you accept a resume upload from React and store it safely?

React puts the file in a FormData object and sends it with fetch without setting Content-Type by hand, so the browser adds the multipart boundary. In Express, use multer only on that route, never as global middleware, with a limit such as a fileSize of 2 MB and a fileFilter that accepts PDF or DOCX; also check the file's first bytes, because the type the browser reports can be faked. Do not keep files on the API server's disk or inside a MongoDB document, which is limited to 16 MB. Upload them to object storage such as S3 under a random key, save only that key, and serve the file through a short-lived signed URL.

31. Before shortlisting, an employer should see a candidate's skills but not their phone number or resume. How do you enforce that in a MERN API?

Decide on the server, for every request. Hiding columns in React does not help, because the full JSON is visible in the browser's developer tools. Build the projection from the viewer and the application status, as in the snippet: at applied the employer gets five profile fields, and after shortlisting also email, phone and the resume key, while passwordHash and internal counters never leave the database. Pass the object to select with lean(), and serve the resume through a short-lived signed link only after the same check. Log each contact reveal with the employer and the time, and add a test that compares the response keys for both statuses, so a new field never leaks by default.

Example
const { find } = require('mingo');
const BASE = { _id: 0, name: 1, headline: 1, skills: 1, city: 1, experienceYears: 1 };
const CONTACT = { email: 1, phone: 1, resumeKey: 1 };
const candidateFields = (application) => // decided on the server for every request
  ['shortlisted', 'interviewed', 'hired'].includes(application.status) ? { ...BASE, ...CONTACT } : BASE;
const candidate = { _id: 'C1', name: 'Asha Rao', headline: 'MERN Developer', skills: ['React', 'Node.js'],
  city: 'Pune', experienceYears: 2, email: 'asha@example.com', phone: '98xxxxxx01',
  resumeKey: 'resumes/9f2c.pdf', passwordHash: '$2b$12$examplehash', otpAttempts: 3 };
for (const status of ['applied', 'shortlisted'])
  console.log(status, Object.keys(find([candidate], {}, candidateFields({ status })).all()[0]));
// route: User.findById(application.candidateId).select(candidateFields(application)).lean()

32. How do you call the Express API from Redux Toolkit with createAsyncThunk and show loading and error states?

createAsyncThunk wraps an async function and dispatches three actions: pending, fulfilled and rejected. The slice handles them in extraReducers to set status, items and error, and components read status to show a spinner or a message. Because fetch does not throw on HTTP errors, the thunk checks res.ok and calls rejectWithValue with the server's message, so the screen says Search is down instead of a vague error. In the run, the status went from loading to succeeded for Pune, then to failed with that message when the API answered 503 for another city. If many screens need caching and refetching, RTK Query from the same package saves writing this by hand.

Example
const { configureStore, createSlice, createAsyncThunk } = require('@reduxjs/toolkit');
const fetchJobs = createAsyncThunk('jobs/fetch', async (city, { rejectWithValue }) => {
  const res = await fetch(`${API}/api/jobs?city=${encodeURIComponent(city)}`);
  if (!res.ok) return rejectWithValue((await res.json()).error); // fetch does not throw on 503
  return res.json();
});
const jobsSlice = createSlice({
  name: 'jobs', initialState: { items: [], status: 'idle', error: null }, reducers: {},
  extraReducers: (b) => b
    .addCase(fetchJobs.pending, (s) => { s.status = 'loading'; s.error = null; })
    .addCase(fetchJobs.fulfilled, (s, a) => { s.status = 'succeeded'; s.items = a.payload; })
    .addCase(fetchJobs.rejected, (s, a) => { s.status = 'failed'; s.error = a.payload ?? a.error.message; }),
});

33. After an employer posts a job, the job list in the app still shows old data. How do you keep server data in sync on the client?

The list was fetched and cached before the new job existed, and nothing told the cache to refresh. With RTK Query, give the list query providesTags with a Job tag and the createJob mutation invalidatesTags with the same tag; when the mutation succeeds, every mounted query with that tag refetches. With TanStack Query, call queryClient.invalidateQueries with the jobs query key in the mutation's onSuccess. For a small change, such as closing one job, you can write the returned job into the cache instead of refetching. With plain Redux, dispatch an action that adds the job from the response. Then decide whether other users' changes need polling, refetch on window focus or a real-time push.

34. Build the aggregation behind "applications per job, split by status" for the logged-in employer.

Start with $match on employerId taken from req.user, so the pipeline sees only this employer's data and can use an index on employerId and jobId. The first $group counts each pair of job and status. The second $group rolls those counts up per job, summing a total and pushing status and count pairs, and $arrayToObject turns the pairs into an object React can read directly. In the run, employer E1 gets J1 with 3 applications, 2 applied and 1 shortlisted, and J2 with 1, while employer E9's application never appears. Storing employerId on each application avoids a $lookup to jobs; the copy is safe because a job never changes employer.

Example
const { aggregate } = require('mingo');
const applications = [
  { employerId: 'E1', jobId: 'J1', status: 'applied' },
  { employerId: 'E1', jobId: 'J1', status: 'shortlisted' },
  { employerId: 'E1', jobId: 'J1', status: 'applied' },
  { employerId: 'E1', jobId: 'J2', status: 'applied' },
  { employerId: 'E9', jobId: 'J5', status: 'applied' },
];
console.log(JSON.stringify(aggregate(applications, [
  { $match: { employerId: 'E1' } }, // from req.user, never from the query string
  { $group: { _id: { job: '$jobId', status: '$status' }, n: { $sum: 1 } } },
  { $group: { _id: '$_id.job', total: { $sum: '$n' }, byStatus: { $push: { k: '$_id.status', v: '$n' } } } },
  { $project: { total: 1, byStatus: { $arrayToObject: '$byStatus' } } },
  { $sort: { _id: 1 } },
]))); // J1: total 3 (applied 2, shortlisted 1), J2: total 1

35. How do you show applications per month in Indian time when MongoDB stores every date in UTC?

MongoDB stores dates as UTC instants, and $dateToString or $dateTrunc work in UTC unless you pass a timezone. Grouping in UTC puts an application made at 00:30 IST on 1 October into September, because it is still 30 September in UTC. The snippet groups the same three documents twice: in UTC the months are September 1 and October 2, and with the timezone Asia/Kolkata they are October 2 and November 1. Pass the zone from the API, ideally from the employer's settings, and use the same zone for the chart labels in React. Otherwise everything from the first five and a half hours of each month lands in the previous month.

Example
const { aggregate } = require('mingo');
const applications = [
  { appliedAt: new Date('2026-09-30T19:00:00Z') }, // 1 Oct, 00:30 IST
  { appliedAt: new Date('2026-10-15T06:00:00Z') },
  { appliedAt: new Date('2026-10-31T20:00:00Z') }, // 1 Nov, 01:30 IST
];
const perMonth = (timezone) => aggregate(applications, [
  { $group: { _id: { $dateToString: { format: '%Y-%m', date: '$appliedAt', timezone } }, n: { $sum: 1 } } },
  { $sort: { _id: 1 } },
]);
console.log(JSON.stringify(perMonth('+00:00')));       // UTC: Sept 1, Oct 2
console.log(JSON.stringify(perMonth('Asia/Kolkata'))); // IST: Oct 2, Nov 1

36. A dashboard endpoint awaits three independent queries one after another and takes 900 ms. How do you make it faster, and what happens if one query fails?

Each await waits for the previous query, so three 300 ms queries add up to 900 ms. Because they do not depend on each other, start them together with Promise.all; the handler then waits only for the slowest one, about 300 ms in the run. Promise.all rejects as soon as one query fails, and Express 5 passes that rejection to the error handler, so the whole dashboard returns an error. If a widget may fail on its own, use Promise.allSettled and send partial data with a flag React can show. Parallel queries also take more connections from the Mongoose pool at the same moment, so do not fire hundreds at once.

Example
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const countOpenJobs = () => wait(300, 12);       // each stands in for a 300 ms query
const countApplications = () => wait(300, 340);
const countInterviews = () => wait(300, 9);
(async () => {
  let t = Date.now();
  await countOpenJobs(); await countApplications(); await countInterviews();
  console.log('one by one:', Math.round((Date.now() - t) / 100) * 100, 'ms'); // 900
  t = Date.now();
  const [jobs, apps, interviews] = await Promise.all([countOpenJobs(), countApplications(), countInterviews()]);
  console.log('together:', Math.round((Date.now() - t) / 100) * 100, 'ms', { jobs, apps, interviews }); // 300
})();

37. Express 5 throws an error at startup for app.get('*') when you serve the React build. How do you write the catch-all so /jobs/123 loads but unknown API paths still return JSON?

Express 5 uses a newer path-to-regexp, where a wildcard must have a name, so the bare asterisk throws a missing parameter name error as soon as the route is registered. Write /{*splat}; the braces make it optional, so it also matches the root path. Order matters, as in the snippet: static files from the build folder first, then the API routes, then a JSON 404 for anything else under /api, and only then the catch-all that sends index.html, so React Router can render /jobs/123 after a refresh. Without the /api guard, a mistyped API URL returns HTML and the React code fails with a confusing JSON parse error.

Example
const express = require('express');
const path = require('node:path');
const app = express();
const dist = path.join(__dirname, 'dist'); // output of npm run build
app.use(express.static(dist));
app.get('/api/jobs/:id', (req, res) => res.json({ id: req.params.id }));
app.use('/api', (req, res) => res.status(404).json({ error: 'No such API route' }));
app.get('/{*splat}', (req, res) => res.sendFile(path.join(dist, 'index.html'))); // app.get('*') throws in Express 5
// /jobs/123 and / get index.html, /api/jobs/123 gets JSON, /api/nope gets a JSON 404

38. Where do environment variables live in a MERN app, and why must the React build never hold a secret?

The Express server reads secrets such as MONGODB_URI, JWT_SECRET and payment gateway keys from process.env, set by the host, PM2, Docker or a secret manager, with a .env file only for local development and never committed. React is different: with Vite, only variables starting with VITE_ reach the browser, and their values are written into the JavaScript files at build time. Anyone can read them in the browser's developer tools, and the Vite documentation warns against putting API keys there. So the front end gets only public values, such as the API base URL, and anything secret stays behind an Express route. Changing a VITE_ value needs a new build.

39. How do you test the apply-to-job API so that tests do not depend on each other or on old data?

Run the Express app in-process with Supertest against a separate test database, either a local MongoDB started for the run or mongodb-memory-server, never the shared staging database. Each test creates exactly what it needs in beforeEach, an employer, a job and a candidate, and the suite empties the collections afterwards, so tests pass in any order. Log in through the real login route and reuse the cookie with a Supertest agent, so the auth middleware is tested too. Then cover the cases that matter: 201 for the first application, 409 for a second one, 403 for an employer, an error for a closed job, and check the stored document, not only the response.

40. The job list renders 20 cards, and each card fetches its company name with a separate API call. Why is that slow, and how do you fix it?

This is the N+1 problem across the network: one request for the list plus 20 more, each with its own latency, auth check and database query. On a slow mobile connection, 21 round trips can take seconds, and the server does twenty times the work. Return what the list needs in one response: copy the company name and logo onto each job, use populate with a field list, or use $lookup. For read-only lists, add lean(), because plain objects take much less memory than Mongoose documents, and a projection so the full description is not sent for every card. Check the request count and sizes in the DevTools Network tab.

Ready to check yourself? Take the free MERN Stack mock test

MERN Stack interview questions: Hard questions (experienced)

20 questions

41. Five API calls fail with 401 at the same moment because the access token has expired. How do you make React refresh once and retry them, and how should the server rotate refresh tokens?

On the client, keep one shared refresh promise, as in the snippet: the first 401 starts POST /api/auth/refresh, later 401s wait for it, and each call retries once; in the run, five parallel calls caused one refresh and five 200 replies. If it fails, go to the login page; never loop. Across browser tabs, coordinate with the Web Locks API or BroadcastChannel, or let the server accept the previous token for a few seconds, otherwise two tabs refreshing together look like token theft. On the server, keep access tokens to about 15 minutes, both tokens in httpOnly cookies, store only refresh-token hashes, replace the token on every use, and revoke the family when a used one returns.

Example
let refreshing = null; // one shared refresh for every request that got a 401
async function apiFetch(url, opts = {}) {
  const res = await fetch(url, { ...opts, credentials: 'include' });
  if (res.status !== 401) return res;
  refreshing ??= fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' })
    .finally(() => { refreshing = null; });
  const r = await refreshing;
  if (!r.ok) throw new Error('SESSION_EXPIRED'); // React sends the user to the login page
  return fetch(url, { ...opts, credentials: 'include' }); // retry once, never loop
}
// 5 parallel calls with an expired token: 1 refresh call, then 5 x 200

42. Your MERN API uses cookie-based login. How do you protect it from CSRF, and when is SameSite alone not enough?

With cookies, the browser attaches credentials even to requests another site triggers, so a hidden form on a malicious page could post to your apply or change-email route. SameSite=Lax blocks most cross-site POST requests, but the OWASP CSRF cheat sheet treats SameSite as defence in depth, not a full defence: sibling subdomains count as the same site, browsers differ, and a state-changing GET route still passes. So add a real check: a signed double-submit token tied to the session that React sends in a header, and at least verify the Origin header against an allow-list on every write. Keep CORS strict too, since a permissive CORS setup weakens header-based defences.

43. Express 5 parses query strings differently from Express 4. Does that remove the risk of MongoDB operator injection?

Only partly. Express 5 uses the simple query parser by default, so email[$ne]=x arrives as a plain key with a string value, not a nested object, which closes the classic query-string trick. JSON bodies are different: express.json still turns a body like email with $ne null into an object, and passing that into findOne could match the first user, as the run shows. Defend in layers: validate body types with a schema so email must be a string, enable Mongoose's sanitizeFilter, which wraps nested objects in $eq as the snippet shows, and never build filters from raw req.query or req.body. Check again if anyone switches the query parser back to extended.

Example
const express = require('express');
const mongoose = require('mongoose');
const request = require('supertest');
const app = express();
app.use(express.json());
app.post('/api/login', (req, res) => res.json({ query: req.query, body: req.body }));
(async () => {
  const r = await request(app).post('/api/login?email[$ne]=x').send({ email: { $ne: null }, password: 'x' });
  console.log(r.body.query); // Express 5 "simple" parser: a plain key, no nested object
  console.log(r.body.body.email); // JSON bodies can still carry operators
  console.log(mongoose.sanitizeFilter({ email: r.body.body.email })); // wrapped in $eq
})();

44. You are reviewing a pull request for PATCH /api/applications/:id/status, where an employer shortlists or rejects a candidate. What do you check before approving?

First, authorisation on the object: the code must confirm the application belongs to a job of the logged-in employer, ideally by updating with a filter that contains both the application id and the employer id. Otherwise any employer can change any application by trying ids, an IDOR. Second, input: the status must be an allowed value and the change must be a valid move, so rejected cannot jump to hired. Third, side effects: the candidate is notified once, after the write succeeds. Fourth, an audit entry of who changed what and when, because hiring decisions get disputed. Finally, tests for another employer's id and for an invalid move.

45. Design the MongoDB data model for a job portal with a few lakh jobs and many lakh applications, starting from the read patterns.

I list the hot screens first: job search with filters, job details, a candidate's own applications, and the employer's applicant list. Jobs hold what search needs (title, city, skills, salary range, work mode, status, createdAt) plus a copied company name and logo, so lists need no join; when a company renames itself, a background job updates its jobs. Applications are a separate collection with jobId, candidateId, employerId, status and a small copy of the candidate's name and headline. Indexes follow the queries, equality fields before the sort: status, city, createdAt for search; jobId, status for applicants; candidateId, createdAt for my applications, because the unique jobId plus candidateId index cannot serve a query on candidateId alone.

46. When a candidate applies, the app creates the application and increments applicationsCount on the job. Do you need a multi-document transaction?

Not always. A write to a single document is atomic in MongoDB, and a unique index on jobId and candidateId already blocks duplicate applications, even when the button is clicked twice. The risk is the counter: if the insert succeeds and the $inc fails, the count drifts. If the number is only shown on the job card, insert first, then $inc, and let a nightly job recount. If it drives billing, such as a plan that allows 500 applications, use a transaction with session.withTransaction, which needs a replica set or a sharded cluster, or count the applications with an index instead of storing a counter. MongoDB's documentation notes that transactions usually cost more than single-document writes.

47. A search page needs the results, the total count and the counts per city and work mode in one request. How do you build it?

Run $match first with the user's filters, so the query can use an index, then $facet to run several sub-pipelines over the same matched documents: one sorts, skips and limits for the current page, one counts the total, and two use $sortByCount for the filter chips. In the run, three open jobs match: the first page shows two titles, the total is 3, Pune has 2 and Noida 1, and remote 2 against office 1. Know the limits: the whole $facet output must fit in one 16 MB document, and $facet as the first stage cannot use indexes. On large collections these counts are costly, so cache them briefly or use a search engine.

Example
const { aggregate } = require('mingo');
const jobs = [
  { title: 'React Developer', city: 'Pune', workMode: 'remote', status: 'open' },
  { title: 'Node.js Developer', city: 'Pune', workMode: 'office', status: 'open' },
  { title: 'MERN Developer', city: 'Noida', workMode: 'remote', status: 'open' },
  { title: 'QA Engineer', city: 'Noida', workMode: 'office', status: 'closed' },
];
const [page] = aggregate(jobs, [
  { $match: { status: 'open' } }, // filter first, so an index can be used
  { $facet: {
    results: [{ $sort: { title: 1 } }, { $skip: 0 }, { $limit: 2 }, { $project: { _id: 0, title: 1 } }],
    total: [{ $count: 'n' }],
    byCity: [{ $sortByCount: '$city' }],
    byMode: [{ $sortByCount: '$workMode' }],
  } },
]);
console.log(JSON.stringify(page));
// results: MERN Developer, Node.js Developer | total 3 | Pune 2, Noida 1 | remote 2, office 1

48. Build a hiring funnel per job, from applied to shortlisted to interviewed to hired, with conversion rates. What data makes it correct?

Storing only the current status breaks a funnel: a candidate rejected after the interview counts as rejected and disappears from the interviewed step. So store the furthest stage reached, or a status history, and count each step as stage greater than or equal to that step. The pipeline groups by job with $cond sums and adds rounded percentages, and every division is guarded with $cond, because a job with no interviews yet would make $divide fail the whole query. In the run, J1's 10 applications give 5 shortlisted, 3 interviewed and 1 hired, so 10 percent overall and 33.3 percent from interview to hire, while J2 gets null instead of an error.

Example
const { aggregate } = require('mingo');
// stage = furthest step reached: 1 applied, 2 shortlisted, 3 interviewed, 4 hired
const applications = [
  ...[4, 3, 3, 2, 2, 1, 1, 1, 1, 1].map((stage) => ({ jobId: 'J1', stage })),
  ...[2, 1, 1].map((stage) => ({ jobId: 'J2', stage })), // nobody interviewed yet
];
const reached = (n) => ({ $sum: { $cond: [{ $gte: ['$stage', n] }, 1, 0] } });
const pct = (part, whole) => ({ $cond: [{ $eq: [whole, 0] }, null, // guard: $divide by 0 fails the query
  { $round: [{ $multiply: [{ $divide: [part, whole] }, 100] }, 1] }] });
console.log(aggregate(applications, [
  { $group: { _id: '$jobId', applied: { $sum: 1 }, shortlisted: reached(2), interviewed: reached(3), hired: reached(4) } },
  { $addFields: { hirePct: pct('$hired', '$applied'), interviewToHirePct: pct('$hired', '$interviewed') } },
  { $sort: { _id: 1 } },
]));
// J1: 10, 5, 3, 1, hirePct 10, interviewToHirePct 33.3 | J2: 3, 1, 0, 0, hirePct 0, interviewToHirePct null

49. The jobs list takes 3 seconds to appear. Which tool would you use in each MERN layer, React, Express, Mongoose and MongoDB, to find the slow part?

Measure each hop before changing code. In the browser, the DevTools Network tab shows how long the API call waits for its first byte and how large the response is; if the API answers in 200 ms, the delay is in React, so record with the React Profiler and the Performance panel to find slow renders or a heavy bundle. In Express, add a Server-Timing header that splits auth, database and serialisation time. Mongoose debug mode, mongoose.set('debug', true), logs every query it sends, which exposes N+1 patterns. In MongoDB, run explain with executionStats on the slow query and compare documents examined with documents returned.

50. Where would you add caching in a MERN job portal between the browser and MongoDB, and how do Express ETags and Redis fit in?

Cache by layer. React build files get long-lived caching on a CDN with content hashes in the file names, while index.html is revalidated, so a new release shows up at once. Public API responses such as featured jobs can carry Cache-Control: public, max-age=60, and Express adds a weak ETag to res.json by default, so a repeat request with If-None-Match gets 304 with an empty body, as in the run; that saves bandwidth, not the database query. Expensive shared results such as filter counts go in Redis with a short expiry and are deleted when a job changes. Never put per-user data in a shared cache.

Example
const express = require('express');
const request = require('supertest');
const app = express(); // res.json() gets a weak ETag by default
app.get('/api/jobs/featured', (req, res) => {
  res.set('Cache-Control', 'public, max-age=60'); // browsers and CDN may reuse it for 60 s
  res.json([{ id: 'J1', title: 'MERN Developer', city: 'Pune' }]);
});
(async () => {
  const first = await request(app).get('/api/jobs/featured');
  const again = await request(app).get('/api/jobs/featured').set('If-None-Match', first.headers.etag);
  console.log(first.status, '->', again.status, again.text.length); // 200 -> 304 0
})();

51. An employer wants to download 2 lakh applications as a CSV file. How do you build the export without loading everything into memory or slowing other users?

Stream it. A Mongoose query with lean() and cursor() gives a readable stream, a Transform turns each document into a CSV line, and stream.pipeline sends it to the response, so only a small batch sits in memory, backpressure is handled and everything is closed on error. The snippet ran with 2 lakh generated rows: 200,001 records with the header. Quote every cell, and put an apostrophe before values that start with =, +, -, @, a tab or a line break, or their full-width forms, as OWASP lists, so spreadsheets do not run them as formulas. Select only the needed fields, and for very large exports build the file in a background job and email the employer a download link.

Example
const { Transform } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const RISKY = /^[=+\-@\t\r\n=+-@]/; // OWASP list: incl. tab, CR, LF, full-width = + - @
const cell = (v) => { const s = String(v ?? '');
  return '"' + (RISKY.test(s) ? "'" + s : s).replace(/"/g, '""') + '"'; };
async function sendCsv(res, cursor) {
  res.set({ 'Content-Type': 'text/csv; charset=utf-8',
    'Content-Disposition': 'attachment; filename="applications.csv"' });
  res.write('name,email,status\n');
  const toRow = new Transform({ objectMode: true,
    transform(a, _enc, cb) { cb(null, [a.name, a.email, a.status].map(cell).join(',') + '\n'); } });
  await pipeline(cursor, toRow, res); // waits whenever the client reads slowly
}
// route: await sendCsv(res, Application.find({ jobId }).select('name email status').lean().cursor());

52. The app runs behind Nginx, and every user seems to have the same IP in logs and rate limits, while express-session refuses to set its Secure cookie. Why, and how do you fix it?

Express sees the TCP connection from Nginx, so req.ip is the proxy's address and req.protocol is http even when the user is on HTTPS. Every user then shares one rate-limit bucket, and express-session will not set a Secure cookie on what looks like a plain HTTP request. Set trust proxy to the exact number of proxies in front of Node, here 1, as in the run, and make sure Nginx overwrites X-Forwarded-For rather than passing on whatever the client sent. Setting it to true trusts any header a client invents. express-rate-limit even logs a validation error when it sees X-Forwarded-For while trust proxy is off.

Example
const express = require('express');
const request = require('supertest');
const app = express();
app.get('/whoami', (req, res) => res.json({ ip: req.ip, protocol: req.protocol }));
const viaNginx = () => request(app).get('/whoami') // headers Nginx would add
  .set('X-Forwarded-For', '49.36.10.5').set('X-Forwarded-Proto', 'https');
(async () => {
  console.log((await viaNginx()).body); // the proxy's own address, http
  app.set('trust proxy', 1);            // exactly one proxy in front of Node
  console.log((await viaNginx()).body); // { ip: '49.36.10.5', protocol: 'https' }
})();

53. Design a release pipeline for a MERN app from pull request to production, including index changes and rollback.

On every pull request, CI runs lint, unit tests and API tests against a throwaway MongoDB, then builds the React app. After the merge, build one artifact, for example a Docker image tagged with the commit, and deploy that same image to staging and then to production, changing only environment variables. Run a smoke test after each deploy. Indexes need care: Mongoose autoIndex builds indexes when the app starts, which suits development but not large production collections, so turn it off there and create indexes as a separate step before the code that needs them. Keep changes backward compatible, so the previous image can be redeployed, and drop old fields a release later.

54. A Mongoose plugin adds companyId to every find so that one company never sees another's jobs. Which Mongoose calls can still leak data across companies, and how do you close each one?

Query middleware covers only the operations it is registered for: hook distinct, updates and replaces too, and block estimatedDocumentCount and bulkWrite, which take no tenant filter. On create, pre validate overwrites any companyId from the body (insertMany too). immutable: true drops it from a $set, but replacements and an upsert's $setOnInsert bypass that, so the query hook forces it there. Aggregations skip query middleware and are not cast, so the aggregate hook adds a $match with a real ObjectId; a $lookup into another collection needs its own. populate is scoped only if the referenced model uses the plugin. Model.collection skips every hook, and each hook throws without a tenant, so cron jobs fail instead of reading everything.

Example
const mongoose = require('mongoose');
const { AsyncLocalStorage } = require('node:async_hooks');
const tenant = new AsyncLocalStorage(); // Express: app.use((req, res, next) => tenant.run(req.user.companyId, next))
function tenantPlugin(schema) {
  const id = () => { const t = tenant.getStore(); // fail closed: no tenant, no query
    if (!t) throw new Error('No tenant in context'); return new mongoose.Types.ObjectId(t); };
  schema.add({ companyId: { type: mongoose.Schema.Types.ObjectId, required: true, immutable: true } });
  schema.pre('validate', function () { if (this.isNew) this.companyId = id(); }); // overwrite any body value
  schema.pre(/^(find|count|distinct|update|delete|replace)/, function () {
    const companyId = id(), u = this.getUpdate(); this.where({ companyId });
    if (u && /replace/i.test(this.op)) u.companyId = companyId; // a replacement is a whole document
    if (u?.$setOnInsert) delete u.$setOnInsert.companyId; // an upsert takes companyId from the filter
  });
  schema.pre('aggregate', function () { this.pipeline().unshift({ $match: { companyId: id() } }); }); // not cast: pass ObjectId
  schema.pre(['estimatedDocumentCount', 'bulkWrite'], function () { throw new Error('Not tenant-safe'); });
}
const Job = mongoose.model('Job', new mongoose.Schema({ title: String, status: String }).plugin(tenantPlugin));

55. You lead four developers on a MERN product. How do you split work between front end and back end so nobody waits for anyone else?

Agree on the API contract first. For each feature the team writes down the endpoints, request and response shapes and error codes, in OpenAPI or a shared zod schema, and reviews it in a short meeting. Front-end developers then build against a mock server or MSW handlers that return exactly those shapes, while back-end developers build the real routes and tests. Feature flags let unfinished work merge every day without users seeing it. Give each feature one owner from screen to database, so somebody is accountable for the whole flow, and ask developers to review pull requests across the boundary, so back-end people see how their responses are used.

56. How can the React form and the Express route share one validation schema, and what problems does that prevent?

Put the schema in a shared package, for example a workspace folder in a monorepo, here written with zod, and import it in both places: the React form uses it for instant feedback and the Express route parses every request with it, so the rules cannot drift apart. The snippet shows a cross-field rule both sides get for free: a maximum salary of Rs 6 lakh below a minimum of Rs 9 lakh fails with a message on salaryMax. With TypeScript, the inferred type also catches a renamed field at build time. The server still parses every request, because a browser check can be skipped, and older app versions may send old shapes.

Example
// shared/jobInput.js: imported by the React form and by the Express route
const { z } = require('zod');
const JobInput = z.object({
  title: z.string().trim().min(3, 'Title is too short'),
  city: z.string().trim().min(2),
  salaryMin: z.number().int().nonnegative(), // rupees per year
  salaryMax: z.number().int().positive(),
}).refine((j) => j.salaryMax >= j.salaryMin, { message: 'Must be at least the minimum', path: ['salaryMax'] });
const r = JobInput.safeParse({ title: 'MERN Developer', city: 'Pune', salaryMin: 900000, salaryMax: 600000 });
console.log(r.success, r.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`));

57. An employer wants to select 50 applications and shortlist them in one click. How would you design that API?

One request instead of 50: POST /api/applications/bulk-status with the list of ids and the new status. Validate on the server: at most 100 ids, each a valid ObjectId, and an allowed status. Apply ownership inside the filter itself, an updateMany on ids in the list and employerId equal to the user's employer, so other companies' ids are simply not matched. Report the result honestly, with the matched and modified counts and the ids that were skipped, because some candidates may have withdrawn in the meantime. Send candidate notifications through a queue after the write, and keep the call safe to retry, since setting the same status twice changes nothing.

58. Design error handling across the whole MERN stack so a user sees a helpful message and you can still find the cause in the logs.

Give every request an id: Express creates one or takes it from the load balancer, adds it to every log line and returns it in an X-Request-Id header. Every error leaves the API in one shape: a stable code, a safe message, optional field errors and the request id, while the error middleware logs the full stack with the user id but never passwords or tokens. In React, the fetch wrapper turns that shape into one error type; forms show field messages, other screens show a toast with the request id, and error boundaries catch rendering crashes and report them to a tool such as Sentry. Alert on error rates, not on every single error.

59. How do you build an optimistic Save job button with rollback in Redux Toolkit?

Update the screen before the server answers, and undo it if the request fails. The thunk receives the job id and the wanted state, saved true or false, instead of a toggle, so the request is idempotent, PUT to save and DELETE to remove, and the rollback simply applies the opposite state. The pending case marks the job at once and the rejected case puts it back. In the run, saving J2 showed it immediately, the failed request removed it again, and unsaving J1 worked. Show a short toast on rollback. If a user taps quickly several times, ignore taps while that job's request is running, or refetch, as the RTK Query documentation suggests for overlapping updates.

Example
const { configureStore, createSlice, createAsyncThunk } = require('@reduxjs/toolkit');
const setSaved = createAsyncThunk('saved/set', async ({ jobId, saved }) => {
  const res = await fetch(`${API}/api/saved-jobs/${jobId}`,
    { method: saved ? 'PUT' : 'DELETE', credentials: 'include' });
  if (!res.ok) throw new Error('Could not update saved jobs');
});
const mark = (s, id, on) => { s.ids = s.ids.filter((x) => x !== id); if (on) s.ids.push(id); };
const savedSlice = createSlice({
  name: 'saved', initialState: { ids: ['J1'] }, reducers: {},
  extraReducers: (b) => b
    .addCase(setSaved.pending, (s, a) => mark(s, a.meta.arg.jobId, a.meta.arg.saved))    // show now
    .addCase(setSaved.rejected, (s, a) => mark(s, a.meta.arg.jobId, !a.meta.arg.saved)), // undo
});

60. Tell me about a bug you fixed that crossed React, Express and MongoDB. How would you answer with the STAR method?

Pick a real bug you traced yourself, and tell it as situation, task, action and result. For example: "After a release, candidates saw Apply instead of Applied on jobs they had already applied to, and 409 errors rose because they clicked again. I had to find the cause that day. The Network tab showed that GET /api/me/applications now returned populated job objects, because a teammate had added populate for another screen, while React still compared plain id strings, so nothing matched. I returned a separate list of job ids, compared ids as strings in React and added an API contract test. The 409s fell back to normal the next day." Then say what changed in reviews.

Practice questions for November 2026

New every month

3 questions from the MERN Stack mock test, the way they appear in it. A new set comes on the 1st of every month. Pick your answer, then open it.

  1. FresherMongoDB Queries and Modelling

    Which fields does this query return for each matching user?

    db.users.find(
        { city: "Jaipur" },
        { name: 1, _id: 0 }
    )
    • Nothing: a projection cannot mix 1 and 0
    • name and _id
    • Only name
    • Every field except name
    Show the answer

    Answer: Only name. _id is returned by default, so the projection turns it off with _id: 0, leaving only name. Mixing 1 and 0 is an error for normal fields, but _id is the one field that may be excluded inside an inclusion projection.

  2. Intermediate (1-5 years)React State and Data Fetching

    A component keeps firstName, lastName and fullName in three useState calls and fullName sometimes goes stale. What is the better design?

    • Compute fullName during render from firstName and lastName
    • Move fullName into Context, so that every child can fix it
    • Sync fullName with a useEffect that runs on every render
    • Store fullName in a ref, so that it never triggers renders
    Show the answer

    Answer: Compute fullName during render from firstName and lastName. Values that can be derived from other state should not be stored separately, because two copies drift apart. const fullName = firstName + ' ' + lastName is always right. Syncing with an effect adds an extra render and still shows a stale frame.

  3. Experienced (5+ years)Node.js Runtime

    Logins slow down sharply under load. Each uses crypto.pbkdf2 (async) and about 20 run at once. What is a likely cause?

    • Node starts a new process for each pbkdf2 call, which costs whole seconds per login
    • libuv's thread pool has 4 threads by default, so the other hashes wait in a queue
    • The async version caches every hash, so the cache fills and slows each lookup
    • pbkdf2 runs on the main thread, so it blocks the event loop for every request
    Show the answer

    Answer: libuv's thread pool has 4 threads by default, so the other hashes wait in a queue. Async crypto functions such as pbkdf2 and scrypt run on libuv's pool, which has 4 threads unless UV_THREADPOOL_SIZE is set. With 20 at once, 16 queue up, and file system calls share the same pool. Tune the pool, the cost factor, or scale out.

Take the full MERN Stack mock test

Ready to apply?

Browse the open jobs on CoreHRx. Create a free profile once and apply with it.