Skip to content

MEAN Stack Online Assessment Questions & Answers

40 questions for the online assessment stage — 15 easy, 25 medium.

About the online assessment round

Most companies start with an online test: aptitude and reasoning, a few MCQs on core MEAN Stack concepts, and one or two short hands-on tasks. It filters a large number of applicants, so speed and accuracy both count.

Tips for the online assessment round

  • Practise under a timer: about one minute per MCQ and 15-20 minutes per hands-on task.
  • Read every option before answering; tests often include two nearly correct choices.
  • Use a stable internet connection, keep your camera on and avoid switching tabs in proctored tests.
  • Attempt the questions you are sure about first, then return to the harder ones.
Solved — online assessmentStart 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 zod validation middleware for an Express route in TypeScript.

Save to ▾
Show answer
Reusable middleware with typed output. import { z, ZodSchema } from 'zod'; import { RequestHandler } from 'express'; export const validateBody = (schema: ZodSchema): RequestHandler => (req, res, next) => { const parsed = schema.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ errors: parsed.error.flatten().fieldErrors }); } req.body = parsed.data; next(); }; const createOrder = z.object({ items: z.array(z.object({ productId: z.string(), qty: z.number().int().min(1) })).min(1), address: z.string().min(10) }); router.post('/orders', validateBody(createOrder), ordersController.create);
02

How do you serve an Angular build and an Express API from the same Node server?

Save to ▾
Show answer
Build Angular with ng build, which outputs static files to dist/project/browser. In Express, register API routes under /api first, then serve the static files with express.static, and finally add a catch-all GET route that returns index.html so Angular routing works on refresh. In larger deployments, Nginx or a CDN usually serves the Angular files while Express handles only the API.
03

How should HTTP errors be handled in an Angular application?

Save to ▾
Show answer
Handle them at two levels. A global error interceptor catches HttpErrorResponse, redirects to login on 401, shows a toast for 500 errors and logs details. Component or service code uses catchError to provide fallbacks or show specific messages, such as field errors from a 422 response. Use retry with a delay for transient network failures, and never leave errors unhandled so the UI shows a blank state.
04

Write a debounced search helper in TypeScript using a closure.

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

Provide a configuration object through an InjectionToken and use it in a service.

Save to ▾
Show answer
Tokens carry non-class values. import { InjectionToken, inject, Injectable } from '@angular/core'; export interface AppConfig { apiUrl: string; pageSize: number } export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG'); // app.config.ts providers: [{ provide: APP_CONFIG, useValue: { apiUrl: environment.apiUrl, pageSize: 20 } }] @Injectable({ providedIn: 'root' }) export class OrderService { private config = inject(APP_CONFIG); private http = inject(HttpClient); list() { return this.http.get(`${this.config.apiUrl}/orders`, { params: { limit: this.config.pageSize } }); } }
06

An Angular page needs to show different content for admin and normal users. How would you implement it in the template?

Save to ▾
Show answer
Expose the current user's role from an auth service as a signal and read it in the component with a computed value such as isAdmin. In the template, use @if (isAdmin()) to render admin sections and @else for the normal view, or create a small structural directive for permission checks if this repeats. Remember to also protect routes with guards and enforce permissions on the Express API.
07

Write an Nginx server block that serves Angular and proxies /api to Node.

Save to ▾
Show answer
One domain, no CORS needed. server { listen 80; server_name shop.example.com; root /usr/share/nginx/html; location /api/ { proxy_pass http://api:3000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { try_files $uri $uri/ /index.html; } location ~* \.(js|css|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; } } Angular hashed file names make long caching safe.
08

Your app must call different API base URLs for development, staging and production. How do you configure this in Angular?

Save to ▾
Show answer
Use environment files such as environment.ts and environment.prod.ts with fileReplacements in angular.json build configurations, or load a config.json at startup with provideAppInitializer so one build works in every environment. Expose the URL through an InjectionToken and inject it in services or an interceptor. Never put secrets in these files, because everything in the Angular bundle is public.
09

Write a functional auth guard that redirects unauthenticated users to the login page.

Save to ▾
Show answer
Return a UrlTree to redirect. import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { AuthService } from './auth.service'; export const authGuard: CanActivateFn = (route, state) => { const auth = inject(AuthService); const router = inject(Router); return auth.isLoggedIn() ? true : router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }); }; // { path: 'orders', canActivate: [authGuard], loadComponent: ... }
10

What is the difference between PUT and PATCH?

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

How do real-time features work in a MEAN application?

Save to ▾
Show answer
Use WebSockets, commonly through Socket.IO on the Express server and its client library in an Angular service that exposes events as Observables or signals. The server emits events, such as new chat messages or order status changes, to rooms of interested users. For scaling across instances, add a Redis adapter. Server-sent events are a simpler option for one-way updates like notifications or live dashboards.
12

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

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

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

How does the Node.js event loop affect the way you write Express route handlers?

Save to ▾
Show answer
Every request handler runs on the same main thread, so any synchronous heavy work, such as a large loop, JSON parsing of huge payloads, sync file reads or bcrypt with sync methods, blocks all other requests. Write handlers with async I/O, keep CPU work small, stream large data, and offload heavy jobs to worker threads or a queue. Monitor event-loop lag in production to catch blocking code.
15

Users upload large documents and want to see upload progress. How do you implement it in Angular?

Save to ▾
Show answer
Send a FormData body with HttpClient post and options reportProgress: true and observe: 'events'. Filter the event stream for HttpEventType.UploadProgress to calculate percent from loaded and total, and for HttpEventType.Response to get the final result. Show a progress bar bound to a signal, allow cancelling by unsubscribing, and validate size and type before upload. For very large files, upload directly to storage with pre-signed URLs.
16

What are typed reactive forms?

Save to ▾
Show answer
Since Angular 14, reactive forms are strongly typed. A FormControl<string> knows its value type, so form.value and getRawValue return typed objects and the compiler catches wrong field names. Controls are nullable by default because reset sets them to null; using nonNullable: true or NonNullableFormBuilder resets to the initial value instead. Typed forms make it safe to map form values directly to API request interfaces.
17

What are route guards and what kinds exist in modern Angular?

Save to ▾
Show answer
Guards decide whether navigation can proceed. canActivate checks before entering a route, canActivateChild covers child routes, canDeactivate runs before leaving, often to warn about unsaved changes, and canMatch decides whether a route definition even matches, useful for role-based lazy loading. Modern guards are plain functions using inject(), returning true, false, a UrlTree for redirect, or an Observable or Promise of these.
18

Write a custom validator that rejects passwords without a number and an uppercase letter.

Save to ▾
Show answer
A ValidatorFn returns null or an error map. import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function strongPassword(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const value = control.value as string; if (!value) return null; const ok = /[A-Z]/.test(value) && /\d/.test(value); return ok ? null : { weakPassword: true }; }; } // password: ['', [Validators.required, strongPassword()]] // @if (form.controls.password.hasError('weakPassword')) { ... }
19

A list API that uses Mongoose populate on three references has become slow. How would you improve it?

Save to ▾
Show answer
Check how many queries populate triggers and how much data each returns. Select only needed fields in populate, use lean(), and add indexes on the referenced fields. If the list always needs a customer name, store it with the extended reference pattern to avoid the join entirely. For complex filtering on related data, switch to one aggregation with $lookup and $project, and paginate.
20

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

Load three APIs in parallel with forkJoin and handle a failure in one of them.

Save to ▾
Show answer
Each request gets its own fallback. import { forkJoin, of, catchError } from 'rxjs'; loadDashboard() { return forkJoin({ sales: this.api.getSales().pipe(catchError(() => of(null))), orders: this.api.getRecentOrders().pipe(catchError(() => of([]))), users: this.api.getUserStats().pipe(catchError(() => of(null))) }); } dashboard = toSignal(this.loadDashboard()); // template: @if (dashboard(); as d) { ... d.sales ... } forkJoin emits once, after every inner Observable completes.
22

What is a route resolver and when would you use one?

Save to ▾
Show answer
A resolver fetches data before a route activates, so the component receives ready data instead of showing an empty state first. A functional resolver, ResolveFn<Product>, uses inject() to call a service and returns an Observable or Promise. The data is available through ActivatedRoute or bound inputs. Use it for detail pages that are useless without data, but avoid it for slow calls, because navigation waits.
23

Write a custom type guard to check whether an API response is an error.

Save to ▾
Show answer
A type predicate narrows the union. type ApiError = { error: true; message: string }; type ApiSuccess<T> = { error: false; data: T }; type ApiResult<T> = ApiError | ApiSuccess<T>; function isApiError<T>(res: ApiResult<T>): res is ApiError { return res.error === true; } if (isApiError(result)) { console.error(result.message); } else { render(result.data); } Inside each branch TypeScript knows exactly which fields exist.
24

Create a child component with a signal input and an output that emits when a button is clicked.

Save to ▾
Show answer
The parent passes data in and listens for events. import { Component, input, output } from '@angular/core'; @Component({ selector: 'app-todo-item', template: ` <span>{{ title() }}</span> <button (click)='remove.emit(id())'>Delete</button> ` }) export class TodoItemComponent { id = input.required<number>(); title = input(''); remove = output<number>(); } // parent template // <app-todo-item [id]='t.id' [title]='t.title' (remove)='onRemove($event)' />
25

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

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

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

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

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

Explain optional chaining and nullish coalescing with examples.

Save to ▾
Show answer
Optional chaining (?.) stops evaluation and returns undefined if the value before it is null or undefined, so user?.address?.city never throws. Nullish coalescing (??) provides a fallback only for null or undefined, unlike || which also replaces 0, empty string and false. So settings.pageSize ?? 10 keeps a real value of 0. Both work in TypeScript and in Angular templates.
29

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

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

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

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) { ... }
31

How do you set up an Express project with TypeScript?

Save to ▾
Show answer
Install express and types with npm i express and npm i -D typescript @types/express @types/node. Create a tsconfig with strict mode and a module setting like NodeNext, write code in src and compile to dist with tsc. For development, run TypeScript directly with tsx watch, and use node dist/server.js in production. Type request bodies, params and responses with Request and Response generics or validated schemas.
32

Your Express API is used by thousands of users and occasionally crashes due to an unhandled promise rejection. How do you make it more resilient?

Save to ▾
Show answer
Find the root cause from logs and fix missing await or catch blocks. Use Express 5, which forwards async errors to error middleware, or an async wrapper in Express 4. Add a central error handler, log unhandledRejection and uncaughtException and then exit cleanly. Run under PM2 or a container orchestrator with multiple instances and health checks so a crash restarts one instance while others keep serving.
33

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

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

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

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

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

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

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

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

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

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

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.

Frequently asked questions

What happens in the MEAN Stack online assessment round?

Most companies start with an online test: aptitude and reasoning, a few MCQs on core MEAN Stack concepts, and one or two short hands-on tasks. It filters a large number of applicants, so speed and accuracy both count.

How do I clear the online assessment round?

Practise under a timer: about one minute per MCQ and 15-20 minutes per hands-on task. Read every option before answering; tests often include two nearly correct choices. Use a stable internet connection, keep your camera on and avoid switching tabs in proctored tests.

Which round comes next?

A typical order is online assessment, telephonic screening, one or two technical rounds, a managerial round and HR. Use the other round pages to practise each stage.