Skip to content

2. First collection ​

A collection is declared by a file in server/mongocamp/. The default export describes the documents with a schema:

ts
import { z } from 'zod'

export default defineMongocampCollection({
  name: 'customers',
  schema: z.object({
    name: z.string().min(1),
    email: z.email(),
  }),
  // step 3: refuse invalid documents (the default `'warn'` stores them and logs a warning)
  validation: 'error',
  // step 4: createdAt and updatedAt
  timestamps: true,
  // step 6: one customer per email address
  indexes: [{ fields: { email: 1 }, unique: true }],
})

The lines after the schema come in the next steps.

Name the file like the collection

The client types know the collection by the file name (customers.ts → 'customers'). The server warns at startup when name and the file name differ.

A few rules for schemas:

  • _id is optional in the schema: the server sets it on insert, and every document that is read has one.
  • Describe the documents as they are stored. Fields the behaviours write (createdAt, createdBy, _v, … from step 4) are added to the type by themselves; do not declare them.
  • z.object drops unknown fields. Use z.looseObject to keep them, at the price of a looser type.

Use it in a component ​

useMongocampCollection('customers') is typed by the declaration. The documents arrive decoded: _id is an ObjectId, dates are Dates.

vue
// typed by server/mongocamp/customers.ts: name, email, _id as ObjectId, createdAt as Date
const customers = useMongocampCollection('customers')
const { data: list, refresh } = await useAsyncData('customers', () => customers.find({ sort: ['name'] }))

useAsyncData loads the list during server side rendering and hands it to the browser with the page. ObjectIds and the other BSON values survive that trip: the module serializes them for the payload.

Inserting is one call. The document is typed as the schema's input:

ts
await customers.insert({ name: 'Ada', email: 'ada@example.com' })

Every other method works the same way: find, findPage, findById, count, update, replace, remove, and paginated() for reactive pages. See Client composables.

Released under the MIT License.