Skip to content

Views ​

Since 2.10, a declared collection can have views: named, read-only aggregations with typed parameters and results. The pipeline stays on the server; clients call the view by its name.

ts
// server/mongocamp/orders.ts
import { z } from 'zod'

export default defineMongocampCollection({
  name: 'orders',
  schema,
  views: {
    totalsByCustomer: defineMongocampView({
      params: z.object({ since: z.date() }),
      result: z.object({ _id: z.string(), total: z.number() }),
      pipeline: ({ since }, { user }) => [
        { $match: { createdAt: { $gte: since } } },
        { $group: { _id: '$customer', total: { $sum: '$qty' } } },
      ],
    }),
  },
})

defineMongocampView comes from @sfxcode/mongocamp-server-core.

Calling a view ​

POST /mongodb/collections/orders/views/totalsByCustomer with the body { "params": { "since": { "$date": "2026-01-01T00:00:00Z" } } }. The answer is paged like the other reads (page, rowsPerPage, count, extendedJson).

On the client the call is typed:

ts
const totals = await useMongocampCollection('orders').view('totalsByCustomer', { since: new Date('2026-01-01') })
// { _id: string, total: number }[]

Rules ​

A view is checked the same way as a client's aggregation:

  • Grant: the caller needs the read grant of the collection.
  • Parameters: they are validated by the params schema. Invalid ones get 400 with the issues.
  • Read scope: the caller's scope comes first (owner, tenant, access rules, soft delete).
  • Hidden fields: fields the caller may not read are removed before the pipeline runs.
  • Joined collections: collections used in $lookup or $unionWith need the caller's read grant.

The pipeline is the server's code, so it may use any stage.

The declaration answer lists the views (name, hasParams). The DevTools tab shows them too.

Released under the MIT License.