HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
70 Topics
Chapter•360 Minutes

70 Progressive Questions (Easy to Advanced + Scenarios)

70 comprehensive interview questions spanning database basics, Mongoose ODM abstractions, advanced aggregation pipelines, system architecture, performance tuning, and real-world scenario challenges.

Q11: How does built-in and custom schema validation work in Mongoose?

Mongoose validates documents against schema constraints prior to saving:

  • Built-in: required, min, max, enum, minLength, match (regex).
  • Custom Validator: Defined using the validate key taking a validator function or regex alongside a custom error message string.
Custom Mongoose Schema Validator
const userSchema = new mongoose.Schema({
  phone: {
    type: String,
    validate: {
      validator: function(v) {
        return /\d{3}-\d{3}-\d{4}/.test(v);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
    required: [true, 'User phone number required']
  }
});
💡 Validates input phone strings against regex patterns before writing to the database.
Key Takeaways
  • Validation runs automatically on doc.save().
  • Can enable validation on updates via { runValidators: true } option.
Knowledge Check

Does Model.findByIdAndUpdate() trigger schema validators by default in Mongoose?

Q12: What are Mongoose Virtuals and how do getters and setters work?

Virtuals are document properties that are not persisted to MongoDB database storage. They are computed dynamically at runtime (e.g., combining firstName and lastName into fullName). Getters compute output values, while Setters parse assigned values back into underlying document fields.

Key Takeaways
  • Virtuals consume zero database storage.
  • Enable toJSON: { virtuals: true } options to include virtuals in API JSON payloads.
Knowledge Check

Are Mongoose Virtual attributes stored directly inside MongoDB collection documents?

Q13: What are Mongoose Pre and Post Middleware hooks?

Middleware (also called hooks) are functions passed execution control during document operations.

  • Pre Hooks: Run before an event executes (e.g., hashing password before pre('save')).
  • Post Hooks: Run after an event completes (e.g., sending welcome emails after post('save')).
Pre-Save Password Hashing Middleware
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 10);
});
💡 Intercepts document save events to hash passwords conditionally before writing.
Key Takeaways
  • Supported hook types: Document, Query, Aggregate, Model.
  • Commonly used for password hashing, auditing, and cascading cleanups.
Knowledge Check

Inside a document pre('save') middleware function, what does 'this' refer to?

Q14: What are Indexes in MongoDB, and why are they crucial for performance?

Indexes are specialized B-Tree data structures that store a small portion of the collection dataset in an easily traversable order. Without indexes, MongoDB performs a Collection Scan (COLLSCAN), inspecting every document. With indexes, MongoDB performs an Index Scan (IXSCAN), retrieving matching documents instantly.

Key Takeaways
  • Reduces query time complexity from $O(N)$ to $O(log N)$.
  • Trade-off: Speeds up reads but adds memory overhead and slightly slows writes.
Knowledge Check

Which scan type occurs when a query executes without an applicable index?

Q15: What is the difference between a Single-Field Index and a Compound Index?

  • Single-Field Index: Index constructed on a single key { email: 1 }.
  • Compound Index: Index constructed on multiple keys { status: 1, createdAt: -1 }. The order of fields matters significantly; queries must follow the Equality, Sort, Range (ESR) rule and match index prefix sequences.
Key Takeaways
  • Compound indexes support queries on prefix subsets of fields.
  • Follow the ESR Rule: Equality fields first, Sort fields second, Range fields last.
Knowledge Check

Given a compound index { a: 1, b: 1, c: 1 }, which query CANNOT utilize this index efficiently?

Q16: Explain the ESR (Equality, Sort, Range) Rule for compound indexes.

The ESR Rule guides optimal compound index field placement:

  1. E (Equality): Put fields matched on exact values first (status: 'active').
  2. S (Sort): Put fields used for ordering second (createdAt: -1).
  3. R (Range): Put fields filtered by inequality ranges last (age: { $gt: 21 }).
Key Takeaways
  • Equality fields $ o$ Sort fields $ o$ Range fields.
  • Prevents in-memory sorting operations (SORT stage in explain execution).
Knowledge Check

Applying the ESR rule to find({ status: 'A', age: { $gt: 20 } }).sort({ name: 1 }), what is the optimal compound index order?

Q17: What are Unique, Sparse, and Partial Indexes?

  • Unique Index: Rejects duplicate values for indexed fields.
  • Sparse Index: Only indexes documents that actually contain the indexed field (ignores documents missing the key).
  • Partial Index: Indexes documents satisfying a specified filter expression (partialFilterExpression), reducing index memory footprint.
Key Takeaways
  • Unique indexes enforce database-level uniqueness.
  • Partial indexes save RAM by indexing specific document subsets.
Knowledge Check

Which index type allows unique constraints on optional fields without throwing errors on multiple missing null entries?

Q18: What is a Time-To-Live (TTL) Index and how is it used?

A TTL index is a single-field index on a Date field that automatically removes documents from a collection after a specified duration (in seconds). A background thread wakes up every 60 seconds to purge expired documents. Ideal for sessions, verification OTPs, and temporary logs.

Creating a TTL Index in Mongoose
const sessionSchema = new mongoose.Schema({
  userId: String,
  createdAt: { 
    type: Date, 
    default: Date.now, 
    expires: 3600 // Automatically deletes document after 1 hour (3600s)
  }
});
💡 Configures automatic document deletion 3600 seconds after creation time.
Key Takeaways
  • Automatically purges documents based on date fields.
  • Must be created on single date-type fields.
Knowledge Check

How often does the MongoDB background thread run to delete expired TTL index documents?

Q19: What is a Multikey Index?

When an index is created on a field that contains an array value, MongoDB automatically creates a Multikey Index. It indexes each individual element inside the array separately. Limitations: A compound index can index at most ONE array field.

Key Takeaways
  • Automatically created when indexing array fields.
  • Cannot construct compound multikey indexes spanning multiple array fields.
Knowledge Check

Can a compound index include two separate array fields in MongoDB?

Q20: How do Text Indexes and Geospatial Indexes operate?

  • Text Index: Supports searching string content for keywords, stemming, and relevance scoring ($text: { $search: 'database' }).
  • 2dsphere Index: Supports queries on a two-dimensional sphere (Earth geometry) using GeoJSON objects (Point, Polygon) for proximity queries like $near and $geoWithin.
Key Takeaways
  • Text indexes enable full-text search and keyword relevance ranking.
  • 2dsphere indexes calculate physical spherical distances using GeoJSON.
Knowledge Check

Which GeoJSON type is used to represent location coordinates [longitude, latitude] for 2dsphere queries?