MERN Stack Interview Questions and Answers
Last updated 2026-11-19
MERN interviews test the seams between four technologies: MongoDB for storage, Express and Node.js for the API, and React for the interface. Interviewers ask how you model data in documents, how a React app authenticates against an Express API, where validation lives and what you do when the whole thing needs to be deployed and secured.
This page concentrates on MongoDB and the integration questions, since single-technology depth is covered on the React, Node.js and Express.js pages. MERN is a popular choice for portfolio projects, so expect to be asked about decisions in yours, as the full stack developer questions page also describes.
| Stack | MongoDB, Express, React, Node.js |
|---|---|
| Core topics | Document modelling, Mongoose, REST API, JWT auth, CORS, deployment |
| Questions here | 17 |
Project questions are the real test
Most MERN interviews open with your project. Be ready to draw its data model and say why you embedded some documents and referenced others, show the request path for login, explain how you stored the token, and name something you would change. Saying that you used localStorage for a JWT and now understand the XSS risk is a better answer than pretending it was ideal.
Frequent weak spots
- Treating MongoDB as schema-free and skipping validation, which leaves inconsistent data.
- Using populate in loops and creating N+1 queries.
- Missing indexes on fields used for filtering and sorting.
- Passing request bodies straight into queries, which allows NoSQL operator injection.
- Opening a new database connection per request instead of once at startup.
MERN Stack Interview Questions and Answers: questions with worked answers
1 What is the MERN stack, and how do the parts connect?
easyMongoDB stores JSON-like documents, Express on Node.js exposes a REST API, and React renders the UI in the browser. The flow: React calls the API with fetch or axios, Express routes validate the request and call Mongoose or the driver, MongoDB returns documents, and Express sends JSON back for React to render. Everything uses JavaScript or TypeScript, so models and validation can be shared.
2 How does MongoDB differ from a relational database?
easyMongoDB stores flexible, nested documents in collections instead of rows in tables, and does not require a fixed schema, though you can enforce one with validation. You model for how data is read, embedding related data, rather than normalising and joining. It scales horizontally through sharding. Multi-document transactions are supported on replica sets, but joins are limited to $lookup, so relational data with many cross-entity queries may fit SQL better.
3 When do you embed documents and when do you reference them?
mediumEmbed when the child belongs to one parent, is read together with it and the array stays bounded, such as addresses on a user. Reference when the child is large, shared by many parents or grows without bound, such as comments or orders for a user, because a document is limited to 16 MB and unbounded arrays hurt performance. A hybrid is common: store a reference plus a few copied fields for display.
javascript// embedded: one read gets the whole order { _id, userId, items: [{ sku: 'A1', qty: 2, price: 499 }], total: 998 } // referenced: comments live in their own collection { _id, postId, authorId, text, createdAt }4 Define a Mongoose schema with validation and an index.
mediumA schema defines field types, validators, defaults, and options such as timestamps. Mongoose validates before save, and unique is an index, not a validator, so handle the duplicate key error with code 11000. Add compound indexes for frequent queries and keep passwords out of default selects.
javascriptimport mongoose from 'mongoose'; const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, lowercase: true, trim: true }, passwordHash: { type: String, required: true, select: false }, role: { type: String, enum: ['user', 'admin'], default: 'user' }, }, { timestamps: true }); userSchema.index({ role: 1, createdAt: -1 }); export const User = mongoose.model('User', userSchema);5 What is the difference between populate and $lookup?
mediumpopulate is Mongoose behaviour: it runs a second query to fetch referenced documents and merges them in the application, so it is simple but costs an extra round trip per populated path. $lookup is an aggregation stage that joins collections inside the database in one query, which can be faster for large sets but is more complex and may not use indexes well on the joined side. Use select and lean to limit data.
6 How do indexes work in MongoDB and how do you check a query uses one?
mediumIndexes are B-trees on one or more fields. A compound index follows the same leftmost-prefix and equality-then-sort-then-range ordering rule as in SQL databases. Run explain("executionStats") and check that the winning plan is IXSCAN, not COLLSCAN, and compare totalDocsExamined with nReturned. Too many indexes slow writes.
javascriptdb.orders.createIndex({ userId: 1, createdAt: -1 }); db.orders.find({ userId: 7 }).sort({ createdAt: -1 }).explain('executionStats');7 How do you implement JWT authentication across React and Express?
mediumOn login Express checks the bcrypt hash and returns a signed token, ideally in an HttpOnly, Secure, SameSite cookie, with a short expiry and a refresh mechanism. A middleware verifies the token on protected routes and attaches the user to the request. React keeps only user info in state and calls the API with credentials: include. Storing a JWT in localStorage works but exposes it to any XSS, so cookies are safer.
javascript// Express login const token = jwt.sign({ sub: user.id }, process.env.JWT_SECRET, { expiresIn: '15m' }); res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 15 * 60 * 1000 }); res.json({ id: user.id, email: user.email });8 How do you handle CORS between the React dev server and Express?
mediumIn development, either proxy API calls through the Vite or webpack dev server so the browser sees one origin, or enable the cors middleware with an explicit origin and credentials: true when using cookies. In production, serve the built React files from the same origin, or from a CDN with a restricted allowed origin list. A wildcard origin cannot be combined with credentials.
9 How do you structure the folders of a MERN project?
mediumKeep client and server as separate packages in a monorepo, or in two folders. On the server separate routes, controllers, services, models and middleware, with configuration loaded from environment variables. On the client organise by feature, with components, hooks and API modules together. Shared validation schemas can live in a common package. Add a single error-handling middleware on the server.
10 How do you connect to MongoDB properly in Express?
mediumConnect once at startup and reuse the connection, since the driver manages a pool. Start listening only after the connection succeeds, handle connection errors, and close it on SIGTERM. Mongoose buffers commands until connected, which hides failures if you skip the check. Put the connection string in an environment variable and use a MongoDB Atlas user with least privilege.
javascriptawait mongoose.connect(process.env.MONGODB_URI, { maxPoolSize: 20 }); const server = app.listen(PORT); process.on('SIGTERM', () => server.close(() => mongoose.disconnect()));11 How do you paginate a list endpoint?
mediumSkip and limit are easy but get slower on deep pages because MongoDB still walks the skipped documents. For infinite scroll use cursor-style pagination: sort by an indexed field with _id as a tie-breaker and query documents after the last value seen. Return the next cursor to the client, cap the page size and add a total count only when needed, since counting is expensive.
javascriptconst filter = after ? { _id: { $lt: after } } : {}; const items = await Post.find(filter).sort({ _id: -1 }).limit(20).lean(); const next = items.length === 20 ? items.at(-1)._id : null;12 What is NoSQL injection and how do you prevent it?
hardIf you pass a parsed request body straight into a query, an attacker can send an operator object instead of a string, for example {"email": {"$ne": null}}, which matches every user. Validate and coerce input types with a schema library, reject objects where strings are expected, enable Mongoose strictQuery, and use sanitising middleware if needed. Never build queries from raw client JSON or use $where with user input.
javascriptconst { email, password } = z.object({ email: z.string().email(), password: z.string().min(1), }).parse(req.body); // an operator object fails here const user = await User.findOne({ email }).select('+passwordHash');13 Do MongoDB transactions exist, and when do you need them?
hardYes, multi-document ACID transactions are available on replica sets and sharded clusters, started with a session and withTransaction, which retries on transient errors. Single-document operations are already atomic, so good schema design with embedding often avoids them. Use a transaction for cross-document invariants such as moving money between two accounts, and keep it short because it holds resources.
javascriptconst session = await mongoose.startSession(); await session.withTransaction(async () => { await Account.updateOne({ _id: from }, { $inc: { balance: -amt } }, { session }); await Account.updateOne({ _id: to }, { $inc: { balance: amt } }, { session }); }); session.endSession();14 How would you write an aggregation pipeline for total sales per user for the last 30 days?
hardAn aggregation pipeline passes documents through stages. Filter early with $match so an index is used, group with $group and sort the result. Put $match and $sort at the front when possible, use $project to drop unneeded fields, and add allowDiskUse only for very large sorts.
javascriptconst since = new Date(Date.now() - 30 * 24 * 3600 * 1000); const rows = await Order.aggregate([ { $match: { createdAt: { $gte: since }, status: 'paid' } }, { $group: { _id: '$userId', total: { $sum: '$total' }, orders: { $sum: 1 } } }, { $sort: { total: -1 } }, { $limit: 10 }, ]);15 How do you deploy a MERN application?
hardBuild the React app to static files and serve them from a CDN or from Express. Run the API as a container or on a platform service behind HTTPS with several instances, using MongoDB Atlas for the database with IP allow-listing and a restricted user. Keep configuration in environment variables per environment, add health checks, structured logs and a CI pipeline that tests, builds and deploys. Configure client-side routing fallbacks so a refresh on a deep link returns index.html.
16 How do you secure a MERN app end to end?
hardHash passwords with bcrypt or Argon2, put sessions in HttpOnly cookies, validate all input on the server, sanitise operator objects to block NoSQL injection, use helmet, rate limiting and a strict CORS list, avoid dangerouslySetInnerHTML with user data and keep dependencies updated. Never ship secrets in the React bundle, since everything there is public. See web security and OWASP interview questions.
17 What are the limits of MongoDB you should mention honestly?
hardDocuments cap at 16 MB and unbounded arrays are an anti-pattern. Joins and cross-collection transactions are weaker than in SQL, and denormalised copies can drift, so updates must touch every copy. Sharding needs a well-chosen shard key because it is hard to change. Consistency settings such as write concern and read concern need deliberate choices. Choose it for flexible, document-shaped data, not by default.
18 How do you test the API and the React client of a MERN app?
hardTest the API with supertest against the app instance and a test database, such as mongodb-memory-server, for fast isolation. Test React components with React Testing Library, mocking network calls with Mock Service Worker. Cover the main journeys, such as sign up, login and create item, with a small number of Playwright end-to-end tests.
javascriptimport request from 'supertest'; test('rejects bad login', async () => { const res = await request(app).post('/api/login').send({ email: 'a@b.in', password: 'wrong' }); expect(res.status).toBe(401); });
Frequently asked questions
Is MERN still a good stack for jobs?
Yes. JavaScript-everywhere stacks remain common at startups and service companies, though many teams now use Next.js or TypeScript with PostgreSQL instead of MongoDB.
Should I use TypeScript with MERN?
It is increasingly expected. Typed models and shared validation schemas reduce bugs across client and server.
MongoDB or PostgreSQL for a new project?
PostgreSQL suits relational data with many joins and strict integrity, while MongoDB suits flexible documents read as a whole. Be ready to defend your choice.
What MERN project impresses interviewers?
One with authentication, a clear data model, pagination, tests, deployment and a README that explains trade-offs, rather than many small clones.
Related guides
- React Interview Questions and Answers (React 19)
- Node.js Interview Questions and Answers (Node 22)
- Express.js Interview Questions and Answers (Express 5)
- Full Stack Developer Interview Questions and Answers
- Redux Interview Questions and Answers (Redux Toolkit)
- Web Security and OWASP Interview Questions and Answers
More in Role-wise Interview Questions by Job and Tech Stack
- Next.js Interview Questions and Answers (Next.js 15)
- NLP Interview Questions and Answers
- Node.js Interview Questions and Answers (Node 22)
- NumPy Interview Questions and Answers
- Pandas Interview Questions and Answers
- Performance Testing and JMeter Interview Questions
- Power BI Interview Questions and Answers
- Probability for Data Science Interview Questions and Answers
- Product Analyst Interview Questions and Answers
- PySpark Interview Questions and Answers
- React Hooks Interview Questions and Answers
- React Interview Questions and Answers (React 19)