Skip to content

Top 50 Most Asked MEAN Stack Interview Questions

The questions that appear most often across company-wise sets — master these first.

Why start here

We count how often each question appears across the 20 company-wise MEAN Stack practice sets on this site and show the 50 most common. They are the safest questions to master first.

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

Write a cart service using signals with computed totals.

RxJS, Signals and State ManagementIn 9 company setsMedium
Save to ▾
Show answer
Expose read-only state and mutation methods. @Injectable({ providedIn: 'root' }) export class CartService { private items = signal<CartItem[]>([]); readonly cart = this.items.asReadonly(); readonly count = computed(() => this.items().reduce((n, i) => n + i.qty, 0)); readonly total = computed(() => this.items().reduce((s, i) => s + i.qty * i.price, 0)); add(product: Product) { this.items.update((list) => { const found = list.find((i) => i.id === product.id); return found ? list.map((i) => (i.id === product.id ? { ...i, qty: i.qty + 1 } : i)) : [...list, { ...product, qty: 1 }]; }); } remove(id: string) { this.items.update((l) => l.filter((i) => i.id !== id)); } }
02

Create a counter component with signal, computed and effect.

Save to ▾
Show answer
Signals keep simple state readable. import { Component, signal, computed, effect } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <p>Count: {{ count() }} (double: {{ double() }})</p> <button (click)='increment()'>+</button> <button (click)='count.set(0)'>Reset</button> ` }) export class CounterComponent { count = signal(0); double = computed(() => this.count() * 2); constructor() { effect(() => console.log('count changed to', this.count())); } increment() { this.count.update((c) => c + 1); } }
03

What is TestBed and how is it used to test an Angular component?

Security, Testing and DeploymentIn 8 company setsMedium
Save to ▾
Show answer
TestBed is Angular's testing utility that creates a test environment similar to the application's. You call TestBed.configureTestingModule with the standalone component in imports and any mock providers, then createComponent to get a ComponentFixture. The fixture gives access to the component instance and its rendered DOM. Call fixture.detectChanges() or await fixture.whenStable() to update the view, then assert on the DOM or component state.
04

What are the main steps to deploy a MEAN application to production?

Save to ▾
Show answer
Build Angular with ng build to produce optimised static files and compile the TypeScript API. Host the Angular files on a CDN, static host or Nginx, and run the API on a VM, container service or Kubernetes with environment variables. Use MongoDB Atlas or a managed replica set. Configure HTTPS, domain DNS, CORS, logging and monitoring, and automate everything through a CI/CD pipeline.
05

What are decorators in TypeScript and how does Angular use them?

Save to ▾
Show answer
Decorators are functions that attach metadata or behaviour to classes, properties, methods or parameters using the @ syntax. Angular uses them to mark classes as framework building blocks: @Component, @Directive, @Pipe and @Injectable, along with property decorators like @Input, @Output, @ViewChild and @HostListener. Angular's compiler reads this metadata at build time to generate efficient rendering and dependency injection code.
06

You need a dropdown value that can only be 'pending', 'shipped' or 'delivered'. How do you model it so invalid values are impossible?

Save to ▾
Show answer
Use a string literal union, type OrderStatus = 'pending' | 'shipped' | 'delivered', or a const array with as const and derive the type from it, so the list can also render the dropdown options. Type the component property and API model with OrderStatus. The compiler then rejects typos like 'shiped'. On the backend, mirror the same values with a Mongoose enum validator.
07

Explain the four types of data binding in Angular.

Save to ▾
Show answer
Interpolation, {{ value }}, displays component data as text. Property binding, [src]='imageUrl', sets a DOM or component property. Event binding, (click)='save()', calls a method when an event fires. Two-way binding, [(ngModel)]='name' or [(value)] with a model input, combines property and event binding so the view and component stay in sync. Data flows one way by default, which keeps changes predictable.
08

How do parent and child components communicate in Angular?

Save to ▾
Show answer
A parent passes data down through inputs, declared with the input() function or the @Input decorator, and the child notifies the parent through outputs, declared with output() or @Output with an EventEmitter. For two-way binding, model() creates a writable input. A parent can access a child directly using viewChild. For unrelated components, use a shared service holding a signal or a BehaviorSubject.
09

What are directives in Angular and what types exist?

Angular Components and TemplatesIn 7 company setsMedium
Save to ▾
Show answer
Directives add behaviour to elements. Components are directives with templates. Attribute directives change appearance or behaviour of an existing element, such as ngClass, ngStyle or a custom appHighlight using host bindings. Structural directives change the DOM layout by adding or removing elements, like the older *ngIf and *ngFor, now largely replaced by built-in control flow. Custom directives keep repeated DOM logic out of components.
10

What is the difference between template-driven and reactive forms in Angular?

Angular Forms and HTTP ClientIn 7 company setsEasy
Save to ▾
Show answer
Template-driven forms build the form model from directives in the template, mainly ngModel, and suit small, simple forms. Reactive forms define the model explicitly in the component with FormControl, FormGroup and FormArray, giving synchronous access, strong typing, easier dynamic fields, observable valueChanges and simpler unit testing. Most enterprise Angular applications use reactive forms for complex or validated forms.
11

How do built-in and custom validators work in reactive forms?

Angular Forms and HTTP ClientIn 7 company setsEasy
Save to ▾
Show answer
Validators are functions that take a control and return null when valid or an error object like { required: true } when invalid. Built-ins include Validators.required, email, minLength, maxLength, pattern, min and max. A custom validator follows the same ValidatorFn signature, for example rejecting weak passwords. Group-level validators can compare fields, such as password and confirm password. Errors are read through control.errors and control.hasError.
12

What is middleware in Express, and what kinds of middleware are there?

Node.js and Express APIsIn 7 company setsEasy
Save to ▾
Show answer
Middleware is a function with access to req, res and next that runs in order for matching requests. Kinds include application-level middleware registered with app.use, router-level middleware on an express.Router, built-in middleware like express.json and express.static, third-party middleware such as cors, helmet and morgan, and error-handling middleware with four arguments. Middleware can end the response or pass control with next().
13

What is the role of a controller-service-repository structure in an Express API?

Node.js and Express APIsIn 7 company setsMedium
Save to ▾
Show answer
Controllers handle HTTP: they read request data, call services and format responses with status codes. Services contain business rules, such as checking stock before creating an order, and are independent of Express. Repositories or models encapsulate database access through Mongoose. This separation makes code easier to test, lets you reuse services in jobs or other transports, and stops route files from turning into large unmaintainable blocks.
14

Serve the built Angular app and the API from one Express server.

Node.js and Express APIsIn 7 company setsMedium
Save to ▾
Show answer
API first, static files next, fallback last. import express from 'express'; import path from 'node:path'; const app = express(); app.use(express.json()); app.use('/api', apiRouter); const dist = path.join(process.cwd(), 'dist/shop/browser'); app.use(express.static(dist, { maxAge: '1y', index: false })); app.get('/*splat', (req, res) => { res.sendFile(path.join(dist, 'index.html')); }); app.listen(process.env.PORT || 3000); The named wildcard follows Express 5 path syntax.
15

What is MongoDB Atlas and what features does it offer?

Save to ▾
Show answer
MongoDB Atlas is the fully managed cloud service for MongoDB on AWS, Azure and Google Cloud. It handles provisioning, replica sets, automated backups, scaling, monitoring, security features like network access lists and encryption, and performance advice such as index suggestions. It also offers Atlas Search, Vector Search and data federation. A free tier makes it popular for learning projects and MEAN prototypes.
16

Write mongosh commands to inspect a slow query and the indexes on a collection.

MongoDB Data Modelling and QueriesIn 7 company setsMedium
Save to ▾
Show answer
Useful diagnostic commands: db.orders.getIndexes() db.orders.find({ status: 'pending', city: 'Pune' }) .sort({ createdAt: -1 }) .explain('executionStats') db.setProfilingLevel(1, { slowms: 100 }) db.system.profile.find().sort({ ts: -1 }).limit(5) db.orders.createIndex({ status: 1, city: 1, createdAt: -1 }) Compare totalDocsExamined with nReturned before and after creating the index.
17

How does JWT-based authentication work end to end in a MEAN application?

Save to ▾
Show answer
The user submits credentials from an Angular form to an Express login route. The server verifies the bcrypt password hash and signs a short-lived access token containing the user id and role, often with a refresh token in an httpOnly cookie. Angular stores the access token in memory, an interceptor attaches it to requests, Express middleware verifies it, and guards control which routes the user can open.
18

What is the difference between an Observable and a Promise?

Save to ▾
Show answer
A Promise represents one future value, starts executing immediately when created and cannot be cancelled natively. An Observable can emit zero, one or many values over time, is lazy so nothing happens until you subscribe, and can be cancelled by unsubscribing. Observables also offer operators like map, filter, debounceTime and switchMap. Angular's HttpClient, router events and reactive forms all expose Observables.
19

What are Angular's lifecycle hooks and when is each typically used?

Angular Components and TemplatesIn 6 company setsMedium
Save to ▾
Show answer
ngOnChanges runs when input values change. ngOnInit runs once after the first inputs are set, used for initial data loading. ngDoCheck allows custom change detection. ngAfterContentInit and ngAfterViewInit run after projected content and the view are ready, used for DOM access. ngOnDestroy runs before removal, used for cleanup. With signals, effect, computed and DestroyRef often replace several of these hooks.
20

What are pipes in Angular and what is the difference between pure and impure pipes?

Angular Components and TemplatesIn 6 company setsMedium
Save to ▾
Show answer
Pipes transform values in templates, such as {{ price | currency:'INR' }}, date, uppercase, json and async. A pure pipe, the default, runs only when its input reference or primitive value changes, so it is very efficient. An impure pipe runs on every change detection cycle, which can hurt performance, and is needed only when output depends on mutable data. Prefer pure pipes or computed signals.
21

Write a custom pure pipe that shortens long text with an ellipsis.

Save to ▾
Show answer
Pipes are standalone by default. import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'truncate' }) export class TruncatePipe implements PipeTransform { transform(value: string | null, limit = 50): string { if (!value) return ''; return value.length > limit ? value.slice(0, limit).trimEnd() + '...' : value; } } // add TruncatePipe to the component's imports, then: // {{ product.description | truncate:80 }} Because it is pure, it reruns only when the input string or limit changes.
22

Write an injectable service that fetches and caches a list of categories.

Save to ▾
Show answer
Cache the Observable with shareReplay so the API is called once. import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, shareReplay } from 'rxjs'; export interface Category { _id: string; name: string } @Injectable({ providedIn: 'root' }) export class CategoryService { private http = inject(HttpClient); private categories$?: Observable<Category[]>; getAll(): Observable<Category[]> { this.categories$ ??= this.http.get<Category[]>('/api/categories') .pipe(shareReplay({ bufferSize: 1, refCount: false })); return this.categories$; } }
23

What is the difference between signal, computed and effect?

Save to ▾
Show answer
signal() creates writable state. computed() derives a read-only value from other signals, is lazily evaluated and memoised, and recalculates only when its dependencies change, for example a cart total from cart items. effect() runs side effects whenever signals it reads change, such as logging or syncing to local storage. Use computed for derived data and keep effects for non-UI side effects, not for setting other state.
24

How do you validate request data in an Express API, and why is it necessary even with Angular validation?

Node.js and Express APIsIn 6 company setsEasy
Save to ▾
Show answer
Frontend validation improves user experience, but anyone can call the API directly with tools like Postman or curl, so the server must validate everything. Use a schema library such as zod, Joi or express-validator in middleware to check types, required fields, lengths and formats, reject unknown fields and return 400 with clear field errors. Mongoose validation is a second layer close to the data.
25

What is the difference between PUT and PATCH?

Node.js and Express APIsIn 6 company setsEasy
Save to ▾
Show answer
PUT replaces the entire resource with the representation sent, so missing fields may be removed or reset, and it is idempotent. PATCH applies a partial update, changing only the fields provided, such as updating only an order's status. In a MEAN API, PATCH with $set in MongoDB is the common choice for edit forms. Validate PATCH bodies so clients cannot modify protected fields like role or price.
26

Which security measures should every Express API in a MEAN app have?

Save to ▾
Show answer
Use HTTPS, helmet for security headers, a strict CORS allowlist, input validation on every route, rate limiting on auth endpoints, body size limits, parameterised queries and stripped MongoDB operators, bcrypt for passwords, secrets in environment variables, and least-privilege database users. Keep dependencies updated with npm audit or Dependabot, log security events and never return stack traces in production.
27

How do you test an Angular service that makes HTTP calls?

Security, Testing and DeploymentIn 6 company setsMedium
Save to ▾
Show answer
Provide provideHttpClient() and provideHttpClientTesting() in TestBed, then inject the service and HttpTestingController. Call the service method and subscribe, use httpMock.expectOne('/api/products') to capture the request, assert its method and body, and flush a fake response. Finally call httpMock.verify() to ensure no unexpected requests remain. This tests the service logic without a real backend.
28

How do you test Express APIs and MongoDB logic in a MEAN project?

Save to ▾
Show answer
Write unit tests for services with Jest or Vitest, mocking external providers. For integration tests, use Supertest to send requests to the exported Express app and mongodb-memory-server or a disposable Docker MongoDB for realistic queries, seeding and cleaning data around each test. Test validation errors, auth failures and permissions, not only happy paths. Run tests in CI on every pull request.
29

Explain the any, unknown and never types in TypeScript.

TypeScript and Modern JavaScriptIn 5 company setsMedium
Save to ▾
Show answer
any switches off type checking, so any operation is allowed and errors move to runtime. unknown also accepts any value but forces you to narrow it with typeof, instanceof or a type guard before using it, making it the safe choice for parsed JSON or caught errors. never represents values that never occur, such as a function that always throws, and is used in exhaustive switch checks.
30

What are generics in TypeScript? Give an Angular-related example.

TypeScript and Modern JavaScriptIn 5 company setsMedium
Save to ▾
Show answer
Generics let you write reusable code that works with many types while keeping type safety, using type parameters like T. For example, an ApiResponse<T> interface can wrap any payload, and a service method get<T>(url: string): Observable<T> returns correctly typed data. Angular's HttpClient.get<User[]>() uses generics so the component knows it receives an array of users, without casting.
31

What are TypeScript utility types such as Partial, Pick, Omit and Record used for?

TypeScript and Modern JavaScriptIn 5 company setsMedium
Save to ▾
Show answer
Utility types transform existing types instead of duplicating them. Partial<User> makes all fields optional, useful for update payloads. Pick<User, 'id' | 'name'> selects fields, and Omit<User, 'password'> removes them, handy for safe API responses. Record<string, number> describes an object map with typed keys and values. Readonly<T> and Required<T> are also common, and they keep frontend and backend models consistent.
32

What is an Angular component and what are its main parts?

Save to ▾
Show answer
A component controls a piece of the screen. It is a TypeScript class decorated with @Component, which provides a selector used as an HTML tag, a template or templateUrl for the view, styles or styleUrl for scoped CSS, and imports for other standalone components, directives and pipes it uses. The class holds data and event handlers, and the template binds to them.
33

What are @defer blocks and how do they help performance?

Angular Components and TemplatesIn 5 company setsMedium
Save to ▾
Show answer
@defer lets you lazy load part of a template and its dependencies only when a trigger occurs, such as on viewport, on interaction, on hover, on idle, on timer or a custom condition with when. Angular automatically splits that code into a separate chunk. You can show @placeholder, @loading and @error blocks. It is ideal for heavy below-the-fold widgets like charts, comments and maps.
34

Write a standalone Angular component that displays a list of products using @for.

Save to ▾
Show answer
Signals and built-in control flow keep it concise. import { Component, signal } from '@angular/core'; import { CurrencyPipe } from '@angular/common'; @Component({ selector: 'app-product-list', imports: [CurrencyPipe], template: ` @for (p of products(); track p.id) { <div class='card'>{{ p.name }} - {{ p.price | currency:'INR' }}</div> } @empty { <p>No products found</p> } ` }) export class ProductListComponent { products = signal([{ id: 1, name: 'Laptop', price: 55000 }]); }
35

Explain dependency injection in Angular.

Save to ▾
Show answer
Dependency injection means a class asks for what it needs instead of creating it. Angular's injector creates instances based on providers and supplies them when a component or service requests them, either through constructor parameters or the inject() function. This decouples code, enables singletons, and lets tests or different environments swap implementations, for example providing a mock AuthService in unit tests.
36

Two components on different pages need to share the selected city filter. How would you implement it?

Save to ▾
Show answer
Create a root-provided FilterService holding the city in a signal, with methods to update it, and inject the service into both components so they share the same instance. For persistence across reloads or shareable links, sync the value to a query parameter or local storage. If many features need shared state with complex updates, consider NgRx SignalStore or NgRx Store.
37

What is RxJS and why is it important in Angular?

Save to ▾
Show answer
RxJS is a library for reactive programming with Observables, streams of values over time, combined using operators. Angular uses it in HttpClient, router events, reactive forms valueChanges and many third-party libraries. It excels at asynchronous workflows such as type-ahead search, polling, websocket streams, retries and combining multiple requests. Signals handle synchronous state well, while RxJS remains the tool for complex event streams.
38

A dashboard needs data from three independent APIs before it can render. How would you load them?

RxJS, Signals and State ManagementIn 5 company setsMedium
Save to ▾
Show answer
Use forkJoin to run all three requests in parallel and emit once when all complete, giving an object or array of results. Handle errors per request with catchError returning a fallback value, so one failed widget does not block the whole dashboard. If any source emits repeatedly, use combineLatest instead. With signals, you could use three httpResource instances and a computed for the combined loading state.
39

What is the difference between valueChanges and statusChanges, and what does updateOn do?

Angular Forms and HTTP ClientIn 5 company setsMedium
Save to ▾
Show answer
valueChanges is an Observable that emits the new value whenever a control or group changes, useful for dependent fields or type-ahead search. statusChanges emits when validation status changes between VALID, INVALID, PENDING and DISABLED. The updateOn option controls when value and validation update: change by default, blur to validate when the field loses focus, or submit to validate only on form submission.
40

Write a group validator that checks password and confirm password match.

Angular Forms and HTTP ClientIn 5 company setsMedium
Save to ▾
Show answer
Group validators see all child controls. export const passwordsMatch: ValidatorFn = (group: AbstractControl) => { const pass = group.get('password')?.value; const confirm = group.get('confirm')?.value; return pass && confirm && pass !== confirm ? { passwordMismatch: true } : null; }; form = this.fb.group( { password: ['', Validators.required], confirm: ['', Validators.required] }, { validators: passwordsMatch } ); // @if (form.hasError('passwordMismatch') && form.controls.confirm.touched) { ... }
41

How do you design REST endpoints for a resource like orders, including nested data?

Node.js and Express APIsIn 5 company setsEasy
Save to ▾
Show answer
Use plural nouns and HTTP methods: GET /orders, GET /orders/:id, POST /orders, PATCH /orders/:id and DELETE /orders/:id. For related data, use shallow nesting like GET /users/:id/orders. Express actions that are not CRUD as sub-resources or clear verbs, such as POST /orders/:id/cancel. Support filtering, sorting and pagination with query parameters, return proper status codes and document the API with OpenAPI.
42

How do you use Mongoose with TypeScript?

MongoDB Data Modelling and QueriesIn 5 company setsMedium
Save to ▾
Show answer
Define a TypeScript interface for the document, then create a Schema typed with that interface and a model with model<IUser>('User', userSchema). Mongoose infers types for queries, so findById returns a typed document. For lean queries, results are plain typed objects. Schema options like timestamps add createdAt and updatedAt, and you can type instance methods, statics and virtuals through additional generic parameters.
43

What is the difference between an interface and a type alias in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are open, so declarations with the same name merge, and they can be extended with extends, which suits object models and class contracts. Type aliases can describe unions, intersections, tuples, primitives and mapped types, such as type Status = 'active' | 'blocked'. Many teams use interfaces for object shapes like API models and type aliases for unions and utility compositions.
44

What is type narrowing and what are type guards?

TypeScript and Modern JavaScriptIn 4 company setsMedium
Save to ▾
Show answer
Narrowing is TypeScript refining a broad type to a more specific one inside a code block based on checks. typeof, instanceof, the in operator, equality checks and discriminated union tags all narrow types. A custom type guard is a function returning a predicate like value is Admin, which tells the compiler the type after the check. This makes handling union types, such as API success or error responses, safe.
45

Write a debounced search helper in TypeScript using a closure.

TypeScript and Modern JavaScriptIn 4 company setsMedium
Save to ▾
Show answer
A typed debounce keeps argument types. function debounce<A extends unknown[]>(fn: (...args: A) => void, ms = 300) { let timer: ReturnType<typeof setTimeout> | undefined; return (...args: A) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); }; } const search = debounce((term: string) => console.log('search', term), 400); search('ang'); In Angular you would usually use the RxJS debounceTime operator instead.
46

What are standalone components and why are they now the default?

Save to ▾
Show answer
Standalone components declare their own dependencies in an imports array instead of belonging to an NgModule. Since Angular 19 they are the default, and the CLI generates them without NgModules. They reduce boilerplate, make lazy loading simpler with loadComponent, improve tree shaking and make components easier to understand and test. Applications bootstrap with bootstrapApplication and configure providers in app.config.ts.
47

How does change detection work in Angular, and what does OnPush do?

Angular Components and TemplatesIn 4 company setsMedium
Save to ▾
Show answer
Change detection checks component bindings and updates the DOM when data changes. Traditionally Zone.js patched async APIs and triggered a check of the whole tree after events, timers and HTTP calls. With ChangeDetectionStrategy.OnPush, a component is checked only when an input reference changes, an event fires inside it, an async pipe emits or a signal it reads changes. OnPush with immutable data greatly reduces work.
48

List the Angular CLI commands you use most often in a project.

Save to ▾
Show answer
Common commands: ng new shop-app --style=scss ng serve --open ng generate component features/product-list ng generate service core/auth ng generate guard core/auth --functional ng generate pipe shared/truncate ng build --configuration production ng test ng update @angular/core @angular/cli ng update applies official migrations automatically, which makes version upgrades much easier.
49

What does providedIn: 'root' mean and what are other ways to provide a service?

Save to ▾
Show answer
providedIn: 'root' registers the service with the application's root injector, so one shared instance exists and it is tree-shakable, meaning it is removed from the bundle if unused. You can also provide services in a component's providers array, giving each component instance its own copy, in a route's providers for a lazy feature, or in app.config.ts. The provider location decides scope and lifetime.
50

How is routing configured in a standalone Angular application?

Save to ▾
Show answer
You define a Routes array mapping paths to components, with redirectTo, child routes and a wildcard ** route for 404 pages, and register it with provideRouter(routes) in app.config.ts. The root template contains <router-outlet />, links use routerLink and routerLinkActive, and code navigates with Router.navigate. Features such as withComponentInputBinding let route parameters bind directly to component inputs.

Frequently asked questions

How is this list made?

We count how often each question appears across the 20 company-wise MEAN Stack practice sets on this site and show the 50 most common. They are the safest questions to master first.

Is this enough to clear an interview?

It is the best starting point, not the finish line. After these, practise the company pages for your target employers and the sheets for your weaker topics.