@fastify/mongodb

Official Plugin for the MongoDB Driver

@fastify/mongodb

The @fastify/mongodb plugin wraps the official mongodb driver, manages the connection pool, decorates the app, and closes cleanly on shutdown.

4 min read Level 2/5 #fastify#mongodb#database
What you'll learn
  • Install @fastify/mongodb and the mongodb driver
  • Register with a url and optional forceClose
  • Use app.mongo.db.collection for queries

@fastify/mongodb is a tiny wrapper around the official mongodb driver. It owns the connection lifecycle — you focus on collections and queries.

Install & Register

npm install @fastify/mongodb mongodb
import mongodb from '@fastify/mongodb'

await app.register(mongodb, {
  url: app.config.MONGO_URL,
  forceClose: true,
  database: 'app',
})

forceClose: true lets the plugin terminate in-flight operations during shutdown — useful when SIGTERM has to be honoured quickly.

Querying Collections

app.get('/users', async () => {
  const users = app.mongo.db!.collection('users')
  return users.find({ active: true }).limit(50).toArray()
})

app.post('/users', async (req) => {
  const body = req.body as { email: string }
  const users = app.mongo.db!.collection('users')
  const { insertedId } = await users.insertOne(body)
  return { id: insertedId }
})

Indexes At Boot

Use the onReady hook to ensure indexes exist before serving traffic.

app.addHook('onReady', async () => {
  await app.mongo.db!.collection('users').createIndex(
    { email: 1 },
    { unique: true },
  )
})

This runs once during boot rather than on every request, so production startup is predictable.

@fastify/cookie →