MongoDB (Database Layer)
- What is MongoDB?
MongoDB is a NoSQL document-oriented database that stores data in JSON-like BSON format. It is schema-less, highly scalable, and supports flexible data models. It’s widely used in MERN stack because of its seamless integration with JavaScript. - What is BSON?
BSON (Binary JSON) is a binary representation of JSON. It supports more data types than JSON, like Date, Binary data, and is optimized for storage and retrieval in MongoDB. - Difference between SQL and NoSQL?
- SQL: Relational, structured tables, predefined schema, ACID transactions.
- NoSQL: Non-relational, flexible schema, document/graph/column storage, scalable horizontally.
MongoDB is NoSQL.
- What is a collection in MongoDB?
A collection is like a table in SQL. It holds multiple documents (records). Collections are schema-less, so documents can have different structures. - What is a document in MongoDB?
A document is a record in MongoDB, stored in BSON format. It is equivalent to a row in SQL and consists of key-value pairs. - Explain _id in MongoDB.
Every document has a unique _id field (ObjectId by default) which acts as the primary key. It is automatically generated if not provided. - How to create a database in MongoDB?
use myDatabase
MongoDB will create the database when a collection is first created.
- How to create a collection?
db.createCollection(“users”)
- Difference between find() and findOne().
- find(): Returns all matching documents in a cursor.
- findOne(): Returns the first matching document.
- Explain indexing in MongoDB.
Indexes improve query performance. For example:db.users.createIndex({ name: 1 }) // ascending order
- What are aggregation pipelines?
Aggregation pipelines allow data processing and transformation in stages like $match, $group, $sort. Example:db.orders.aggregate([
{ $match: { status: “completed” } },
{ $group: { _id: “$customerId”, total: { $sum: “$amount” } } }
]) - Difference between updateOne, updateMany, replaceOne.
- updateOne(): Updates first matching document.
- updateMany(): Updates all matching documents.
- replaceOne(): Replaces the whole document.
- Explain Mongoose.
Mongoose is an ODM (Object Data Modeling) library for MongoDB in Node.js. It provides schemas, validation, and model abstraction. - How to define a schema in Mongoose?
const mongoose = require(‘mongoose’);
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
const User = mongoose.model(‘User’, userSchema); - Difference between save() and create() in Mongoose.
- save(): Called on an instance of a model; triggers middleware.
- create(): Directly creates a new document; faster but less flexible.
- What is populate() in Mongoose?
populate() allows you to reference documents from another collection. Example:Post.find().populate(‘author’).exec()
- Explain MongoDB transactions.
MongoDB supports multi-document ACID transactions in replica sets. Example:const session = await mongoose.startSession();
session.startTransaction();
// operations
await session.commitTransaction();
session.endSession(); - Difference between embedded documents and references.
- Embedded: Data stored inside a document (fast, denormalized).
- Reference: Stores ObjectId of another document (normalized, flexible).
- How to handle relations in MongoDB?
Use embedded documents or references with populate(). - Explain capped collections.
Capped collections are fixed-size, circular collections, ideal for logging.
Express.js (Backend Layer)
- What is Express.js?
Express.js is a Node.js framework for building web applications and APIs. It simplifies routing, middleware, and request handling. - How to create a simple Express server?
const express = require(‘express’);
const app = express();
app.get(‘/’, (req, res) => res.send(‘Hello MERN’));
app.listen(3000, () => console.log(‘Server running’)); - What is middleware in Express?
Middleware is a function that has access to request, response, and next().
Example:app.use((req, res, next) => {
console.log(‘Request URL:’, req.url);
next();
}); - Difference between app.use and app.get/post.
- app.use(): For middleware, applies to all routes or a path.
- app.get/post(): Defines HTTP GET or POST routes.
- How to handle errors in Express?
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
}); - What is routing in Express?
Routing maps HTTP requests to functions based on URL paths and methods. - How to parse JSON in Express?
app.use(express.json());
- What are route parameters?
Variables in URL path. Example:app.get(‘/user/:id’, (req, res) => {
res.send(req.params.id);
}); - What are query parameters?
Parameters in URL after ?. Example: /user?id=123 → req.query.id. - Explain CORS and handling in Express.
CORS allows cross-origin requests. In Express:const cors = require(‘cors’);
app.use(cors()); - How to serve static files in Express?
app.use(express.static(‘public’));
- Explain Express Router.
Router allows modular routing:const router = express.Router();
router.get(‘/users’, (req, res) => res.send(‘Users’));
app.use(‘/api’, router); - How to connect Express with MongoDB?
const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost:27017/mernDB’); - Difference between PUT and PATCH in Express.
- PUT: Replaces the whole resource.
- PATCH: Updates specific fields.
- What is JWT and how to use in Express?
JWT (JSON Web Token) is used for authentication. Example:const jwt = require(‘jsonwebtoken’);
const token = jwt.sign({ id: user._id }, ‘secretKey’, { expiresIn: ‘1h’ }); - Explain middleware chaining in Express.
Multiple middleware can be executed in order using next().app.get(‘/route’, mw1, mw2, (req,res)=>res.send(‘done’));
- How to handle file uploads in Express?
Use multer library:const multer = require(‘multer’);
const upload = multer({ dest: ‘uploads/’ });
app.post(‘/upload’, upload.single(‘file’), (req, res) => res.send(‘File uploaded’)); - Difference between res.send, res.json, res.end.
- res.send(): Sends string, object, or buffer.
- res.json(): Sends JSON response.
- res.end(): Ends response without data.
- What are environment variables?
Sensitive or config data stored in .env. Example:PORT=5000
DB_URL=mongodb://localhost:27017/mernDBAccess in Node: process.env.PORT.
- How to handle 404 routes?
app.use((req, res) => res.status(404).send(‘Not Found’));
React.js (Frontend Layer)
- What is React.js?
React.js is a JavaScript library for building interactive user interfaces. It uses component-based architecture, virtual DOM, and unidirectional data flow. - Difference between React and Angular?React: Library, uses JSX, component-based, unidirectional data flow.Angular: Framework, uses TypeScript, MVC pattern, two-way data binding.
- What is JSX?
JSX is a JavaScript XML syntax that allows you to write HTML inside JavaScript. Example:const element = <h1>Hello React</h1>;
- What is a component?
A component is a reusable UI element in React.Functional Component: Function-based.Class Component: ES6 class-based. - Explain props in React.
Props (short for properties) are read-only inputs passed from parent to child.function Child({ name }) {
return <h1>Hello {name}</h1>;
} - What is state in React?
State is mutable data managed inside a component. Updating state re-renders the component.const [count, setCount] = useState(0);
- Difference between state and props?Props: Read-only, from parent, immutable.State: Mutable, local to component, managed by the component.
- What are React Hooks?
Hooks allow functional components to use state and lifecycle features.
Examples: useState, useEffect, useRef, useContext. - Explain useEffect.
useEffect handles side effects like API calls, DOM updates, and subscriptions.useEffect(() => {
fetchData();
}, [dependencyArray]); - Explain the virtual DOM.
Virtual DOM is a lightweight copy of the real DOM. React updates the virtual DOM first and then efficiently updates only changed elements in the real DOM. - Difference between controlled and uncontrolled components.Controlled: Form inputs controlled via state.Uncontrolled: Form inputs managed by DOM using refs.
- How to handle forms in React?
Use state for controlled components:<input value={name} onChange={(e)=>setName(e.target.value)} />
- What is lifting state up?
Sharing state between components by moving it to the nearest common parent. - Explain React Router.
React Router manages client-side routing. Example:import { BrowserRouter, Routes, Route } from ‘react-router-dom’;
<BrowserRouter>
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/about” element={<About />} />
</Routes>
</BrowserRouter> - Difference between React Router v5 and v6.v6 uses <Routes> instead of <Switch>.Nested routes and element props replaced component.
- What is Context API?
Allows sharing global state without prop drilling:const ThemeContext = React.createContext();
<ThemeContext.Provider value={theme}>…</ThemeContext.Provider> - What is Redux?
Redux is a state management library for React that uses a central store to manage global state. - Explain Redux flow.
- Action dispatched → 2. Reducer updates state → 3. Store notifies components.
- Difference between Redux and Context API?Context API: Simple global state, best for small apps.Redux: Robust, scalable, middleware support, good for complex apps.
- Explain React.memo.
React.memo prevents unnecessary re-renders by memoizing the component. - What is useRef?
useRef stores mutable references to DOM elements or variables that persist between renders. - What is useCallback and useMemo?
- useCallback: Memoizes functions.
- useMemo: Memoizes computed values.
- Difference between class and functional components.
- Class: State, lifecycle methods, older style.
- Functional: Hooks, simpler, modern approach.
- Explain lifecycle methods in React.
Class components: componentDidMount, componentDidUpdate, componentWillUnmount.
Functional: Use useEffect. - What are higher-order components (HOC)?
HOC are functions that take a component and return a new enhanced component. - Difference between key and ref in React.
- key: Unique identifier for list items, used for rendering optimization.
- ref: Access DOM element or component instance.
- What is suspense and lazy loading?
React.lazy + Suspense allows code splitting and dynamic component loading. - Explain portals in React.
Portals render a child component outside the DOM hierarchy of its parent. - How to optimize React performance?
- Memoization (React.memo, useCallback)
- Avoid unnecessary re-renders
- Code splitting and lazy loading
- Use keys in lists
- What is prop drilling? How to avoid it?
Passing props through multiple levels unnecessarily. Avoid with Context API or Redux.
Node.js (Backend Layer)
- What is Node.js?
Node.js is a JavaScript runtime built on Chrome’s V8 engine. It allows JS to run on the server-side with non-blocking, event-driven architecture. - Difference between Node.js and traditional server?
- Node.js: Non-blocking, single-threaded, event-driven.
- Traditional server: Multi-threaded, blocking I/O.
- Explain event loop in Node.js.
The event loop handles asynchronous operations in a single thread, allowing non-blocking I/O. - What are streams in Node.js?
Streams handle large data efficiently without loading everything in memory. Types: readable, writable, duplex, transform. - What is npm?
Node Package Manager, used to install, manage, and share Node.js packages. - Difference between require() and import?
- require(): CommonJS, used in Node.js.
- import: ES6 module syntax.
- What is middleware in Node.js?
Middleware is a function executed during request-response cycle, typically in Express.js. - Explain error handling in Node.js.
Use try/catch for synchronous code and .catch() or async/await for async code. - How to connect Node.js with MongoDB?
Use mongoose.connect(DB_URL) or native MongoClient. - What is package.json?
package.json stores project metadata, dependencies, scripts, and config. - Explain asynchronous programming in Node.js.
Node.js uses callbacks, promises, and async/await for non-blocking operations. - What is buffer in Node.js?
Buffer stores binary data while reading files or working with TCP streams. - Difference between process.nextTick() and setImmediate()
- process.nextTick(): Executes before the next event loop.
- setImmediate(): Executes in the next event loop iteration.
- How to secure Node.js applications?
- Use HTTPS
- Sanitize inputs
- JWT authentication
- Helmet, rate limiting, CORS
- How to deploy Node.js app?
- Platforms: Heroku, Vercel, Render, AWS EC2
- Build: npm install, node server.js, use PM2 for process management.
Full MERN Stack Integration
- What is the MERN stack?
MERN = MongoDB, Express.js, React.js, Node.js. Full-stack JavaScript for building scalable web apps. - How does data flow in MERN?React sends HTTP request to Express Express handles API and queries MongoDB MongoDB returns data to Express Express sends response to React React updates UI
- How to call API from React?
fetch(‘/api/users’)
.then(res => res.json())
.then(data => setUsers(data));
- How to handle JWT in MERN?
- Generate JWT in Node.js after login
- Send to React, store in localStorage or cookie
- Include JWT in Authorization header for protected routes
- Explain protected routes in MERN.
- Backend: Middleware checks JWT before allowing API access
- Frontend: React checks auth state before rendering component
- What is CORS problem in MERN?
Browser blocks requests from different origin. Solved by cors middleware in Express. - How to connect React with Express?
- Option 1: React frontend calls backend via fetch or axios
- Option 2: Serve React build via Express:
app.use(express.static(‘client/build’));
app.get(‘*’, (req,res) => res.sendFile(path.resolve(‘client’,’build’,’index.html’)));
- What is dotenv in MERN?
.env file stores environment variables like DB URL, JWT secret. Node.js accesses via process.env. - How to handle errors in MERN?
- Backend: Use try/catch and middleware
- Frontend: Use try/catch in API calls, show user-friendly messages
- What is Redux in MERN?
Redux is often used to manage global state across React components, especially for user authentication, cart, or settings. - How to deploy MERN stack app?
- Build React: npm run build
- Serve via Express or host separately
- Deploy MongoDB Atlas for database
- Deploy Node.js server on Heroku, Render, or AWS
- What are WebSockets and Socket.io?
Used for real-time communication in MERN apps, like chat apps or live notifications. - How to handle file uploads in MERN?
- Backend: multer saves files
- Frontend: FormData API to send files via axios
- Explain pagination in MERN.
Backend: Use skip and limit in MongoDB query
Frontend: Display page numbers, call API with page parameter - Tips for optimizing MERN stack app
- Use indexes in MongoDB
- Optimize React rendering (memoization)
- Enable compression in Express
- Lazy load routes and components
- Use CDN for static assets
