Skip to Content

db.ts — MongoDB connection

Path: src/config/db.ts

Before the server accepts real traffic, it must plug in to MongoDB — like plugging in a USB drive where all users and questions live.

connectDB() is called once from index.ts.

Steps inside connectDB()

  1. mongoose.connect(env.MONGODB_URI) — open connection.
  2. Log MongoDB connected.
  3. Index maintenance (one-time compatibility):
    • Drop legacy unique index on UserExtractedQuestion if it lacked questionIndex.
    • syncIndexes() on several collections so queries stay fast and unique rules hold.

Models touched at connect time

Imported only for index sync:

  • UserExtractedQuestion, UserGeneratedPracticeQuestion
  • Practice PYQ taxonomy + questions + user cards
  • Study stats: PracticeAttemptEvent, rollups

Failure behavior

  • Connect failure → startup fails (promise rejects).
  • Index sync warning → logged, server may still run (non-fatal catch).

Models for other collections still work; their indexes sync when Mongoose first uses them.

Last updated on