Skip to content

Declared Collections ​

Since 2.3 a collection can be declared with a schema and behaviours. Any Standard Schema library works: Zod 4, Valibot, ArkType and others. One declaration gives you three things:

  • Types: useMongocampCollection('orders') returns typed, decoded documents on the client (client composables).
  • Validation: documents written through the API are checked against the schema. Invalid ones get 400 with the fields in issues.
  • A MongoDB validator: the schema becomes a $jsonSchema validator of the collection, so documents written by other clients (the shell, other services) are checked too.

Collections without a declaration behave as before.

Declaring a collection ​

In a Nuxt application, every file in server/mongocamp/ declares one collection (default export, defineMongocampCollection is auto-imported):

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

export default defineMongocampCollection({
  name: 'orders',
  schema: z.object({
    customer: z.string().min(1),
    qty: z.int().min(1).default(1),
    status: z.enum(['open', 'done']).default('open'),
    createdAt: z.date(),
  }),
  validation: 'error',
})
FieldDefaultDescription
name—The collection, without database. Name the file like the collection: the client types use the file name, and the server warns when they differ.
databasethe default databaseAnother database.
schema—A Standard Schema of the documents as they are stored. _id needs no field (3.0): the types add _id: ObjectId to read documents and an optional one to inputs, and validation ignores _id unless the schema declares it (a text id, for example).
validation'error' (3.0; 'warn' in 2.x)'off', 'warn' or 'error', see below.
validatorconverted from schemaAn explicit $jsonSchema validator for MongoDB, for schemas that cannot be converted.
indexes—The indexes of the collection (2.4), created at the start.
refs—References to documents of other collections (2.4), for expand on reads.

Layers can declare collections too; a file of the application wins over a layer file with the same name. The directory is the module option server.collectionsDir.

With your own host or the standalone server, register declarations as a feature:

ts
import { collections, defineMongocampCollection } from '@sfxcode/mongocamp-server-core'

await server.use(collections([orders, customers]))

Modes ​

ModeWrites through the APIMongoDB validator
offnot validatednever touched
warnvalidated; invalid documents are logged and written unchangedvalidationAction: 'warn' (MongoDB logs)
error (default since 3.0)invalid documents are refused with 400validationAction: 'error' (MongoDB refuses)

At the start, a declaration without validation checks a sample of up to 200 stored documents and logs a warning with the number of invalid ones, so an upgrade from 2.x shows the collections whose writes would now be refused. validation: 'warn' keeps the 2.x behaviour.

Start with warn on a collection that already has data, check the log, then switch to error.

What is validated, and how ​

The schema validates full documents: insert, insert many, import and replace (PATCH …/documents/{id}). In error mode one invalid document refuses the whole request; the paths of the issues start with its position ([3].qty), for an import with its line number.

Operator updates (PATCH …/{id}/partial, many/update) are checked by the MongoDB validator. Its error has the same shape (code 121, issues).

A valid document is stored as the schema returns it:

  • defaults and transforms apply (qty becomes 1 when it is missing);
  • _id stays the one that was sent;
  • whole numbers are stored as int (or double beyond the int32 range), not as long like other API writes. The schema always sees numbers: the Long values the API decodes are handed over as plain numbers.

Unknown fields

z.object (and Valibot's object) drop fields that are not in the schema, so they are not stored. Use z.looseObject to keep them. The trade-off: the TypeScript type then allows any field name, so a misspelled field is no longer a type error.

Validation runs after every before-hook that changes the document, so fields added by a hook (createdBy) must be in the schema.

Behaviours ​

Since 2.3 a declaration switches behaviours on with one flag each, with defaults that need nothing else; an options object renames fields (dot paths for nested ones). The fields a behaviour writes are added to the document type and to the MongoDB validator; the schema must not declare them, and clients cannot write them.

ts
export default defineMongocampCollection({
  name: 'orders',
  schema,
  timestamps: true, // createdAt, updatedAt
  owner: true, // only the creator writes; reads: 'own' (default), 'all' or a function
  softDelete: true, // deletedAt instead of removing
  versioned: true, // _v, an outdated write answers 409
  audit: true, // before and after of every write, kept 365 days
  protectedFields: ['approved'], // only server code writes them
})

timestamps ​

OptionDefaultDescription
createdAt, updatedAtcreatedAt, updatedAtthe creation and change time
createdBy, updatedBynot writtentrue or a path: the user of the request
preserveOnInsertfalsean insert by an administrator (also one acting for a user) keeps the values it sends for these fields; missing ones are written as usual (2.7.0)
preserveOnUpdatefalsean update or replace by an administrator (also acting) that asks for it with the header X-MONGOCAMP-KEEP-TIMESTAMPS: true keeps the updatedAt / updatedBy it sends; missing ones are written as usual (2.8.0)

timestamps: true is the Mongoose behaviour. Nested paths keep the metadata together:

ts
timestamps: { createdAt: 'metaData.created', updatedAt: 'metaData.updated', createdBy: 'metaData.createdBy', updatedBy: 'metaData.updatedBy' }

The creation values are written once and stay on every later write (also a replace). Clients cannot send them — except with preserveOnInsert, where an administrator's insert keeps them: restores of a backup and imports keep their creation time and users. Every other caller's values are still replaced.

preserveOnUpdate is for maintenance writes — a script that marks its change (updatedBy: 'script:convert') or keeps the change time of a document a person edited. The collection allows it, and each write asks for it: the header X-MONGOCAMP-KEEP-TIMESTAMPS: true (KeepTimestampsHeader of the core), or keepTimestamps: true of a server collection. Both are needed, so the ordinary writes of a backend that acts for its users are still stamped. Only $set of the change fields is kept (no $unset or $inc); the creation fields stay protected. With versioned in mode timestamp the sent updatedAt is also the expected version: the write is checked like any other and does not advance the version, so an edit that a person started before the script still saves. The header has no effect for callers that are no administrators, and on collections without the option.

A schema object that a behaviour writes into (metaData above) exists on every document, so its own fields must be optional — a required field there is refused when the collection is declared.

owner ​

Per-document access without writing routes: the creator owns the document; the owner field is the createdBy of timestamps when set, else owner.

OptionDefaultDescription
read'own''own': only the owner reads; 'all': everybody with the read grant; a function ({ user, collectionName }) => filter
fieldcreatedBy of timestamps, else ownerthe field with the user id
adminBypasstrueadministrators read and write every document
preserveOnInsertfalsean insert by an administrator (also one acting for a user) keeps the owner it sends — imports that create documents for their users; without one the user of the request owns it (2.7.0)

Only the owner updates, replaces, deletes and restores. A document of someone else answers 404, like a missing one, so nobody learns which ids exist; a write of many documents counts it as not matched. The collection grants still apply first: owner rules narrow them, never widen them.

ts
// own documents and the ones shared with the user
owner: { read: ({ user }) => ({ $or: [{ owner: user.userId }, { sharedWith: user.userId }] }) }

Documents stored before the behaviour have no owner: only administrators can change them until the field is set (a migration script with the driver).

A backend that checks its own rules can use the behaviours without giving its users grants: its administrator API key acts for the user of the request (X-AUTH-ACT-AS), so owner, timestamps, versioned and audit see that user while the rights stay the administrator's (2.7.0).

softDelete ​

A delete sets deletedAt (with timestamps also the change time) instead of removing the document. Every read hides deleted documents — lists, counts, exports, aggregations, live updates — and writes cannot reach them.

withDeleted=trueon the read routes, for administrators of the collection (403 for others): deleted documents too
POST …/documents/{id}/restoreremoves the mark (write grant); restore(id) in the client
purgeAfterDaysremoves deleted documents for good after that many days (a TTL index, kept in sync with the option)
fielddefault deletedAt

A unique index declared in indexes ignores deleted documents by itself (partial on { deletedAt: null }), so a deleted value can be used again; a unique index made by hand needs that partial filter too ($exists: false is not allowed in partial indexes).

versioned ​

OptionDefaultDescription
mode'counter''counter': a number _v, increased by every write; 'timestamp': the updatedAt of timestamps is the version (no extra field)
field_vthe counter field
requiredfalsea replace or partial update without version answers 428

A replace or partial update that sends the version of the document it is based on only succeeds when the document still has it — checked in the same write. Otherwise the answer is 409 (code 4092) with the stored document in current, to show or merge; since 2.6 current uses the extendedJson mode of the request (relaxed without); since 2.8 the generated client's update and updateDocumentPartial take it as extendedJson. _v starts at 0. many/update and many/delete are not checked against the version, but count it up. Without version the last write wins. The typed composable sends the version by itself.

audit ​

Every write leaves a record in <AUTH_PREFIX>audit (mc_audit): the operation (insert, replace, update, delete, softDelete, restore), the user, the time and the document before and after. PATCH …/documents/{id} replaces the whole document and is recorded as replace; PATCH …/documents/{id}/partial and many/update are recorded as update. Under X-AUTH-ACT-AS user is the user acted for and actedBy (3.1.1) the administrator who sent the request. retentionDays (default 365) decides how long a record is kept. A write of many documents records up to 10,000 of them and one summary record; an import records the ids only. Records are written after the answer (best effort, like the events).

GET …/documents/{id}/history answers the records of a document to the users who can read it (administrators also of deleted documents), GET /mongodb/collections/{name}/history the records of the collection to its administrators (since, operation). Each record has its own _id, the auditId of the restore below ({ $oid } in Extended JSON, the hex string with extendedJson=plain; the generated client calls it id, declared since 3.1.2). Under X-AUTH-ACT-AS the user acted for decides both (since 3.1.1; before, the administrator's rights let the history of other users' documents through). In the client: history(id), whose records carry id as hex string (3.1.2) for restoreVersion(id, record.id).

Since 2.11 a document can be put back from its history: POST …/documents/{id}/history/{auditId}/restore (?state=before for the state before the write) replaces it through the hooks — validation, behaviours and access rules apply, a versioned document gets a new version (both modes; since 3.2.1 also mode: 'timestamp', which answered 409 before) — or inserts it again when it was deleted. The restore is audited as restore with restoredFrom. It is based on the stored version, so it needs no version from the client and wins over the changes since the record; only a write between its read and its write answers 409. The snapshot comes back as it was, including any timestamps the application writes itself (a metaData.updated goes back in time); the timestamps behaviour sets updatedAt on the restore, an application that keeps its own timestamps writes them after the restore. 400 for a collection without audit, 404 for a record of another document or a document outside the caller's scope. In the client and the server collection: restoreVersion(id, auditId, { state }).

drafts ​

drafts: true (2.11) separates the published state of a document from its working copy:

  • New documents are drafts (_status: 'draft'): readers never see them, in any read path (list, get, count, expand, export, aggregation, live updates).
  • Edits of a published document go to the working copy (_draft) — readers keep getting the published fields, and never _draft.
  • POST …/{id}/publish validates the working copy and makes it the published state (_status: 'published', publishedAt, publishedBy); …/unpublish makes the working copy the document again and hides it; …/discard-draft drops the working copy.
  • Editors read the working copies with drafts=true (find({ drafts: true }), findById(id, { drafts: true })): it needs the write grant and the update access rule, or drafts: { readers }.
  • audit records publish, unpublish and discardDraft; softDelete and versioned combine as usual. An update of many published documents at once is refused.

protectedFields ​

Fields that clients cannot write — inserts and updates drop them, a replace keeps the stored value. Server code can: before-hooks and Nitro plugins (they run after the guard), and writes with the driver (useMongocampCore(), scripts).

Field names (3.2) ​

Since 3.2 the server refuses field names that start with $ (at any depth, { a: { $set: 1 } }) or contain . at the top level ({ 'a.b': 1 }) with 400 and the paths in issues — in every collection, see DOCUMENTS_CHECK_FIELD_NAMES. MongoDB stores them, but a $ name turns into an operator once the document is passed into an update or a filter, and a dotted top-level name cannot be addressed by an update. checkFieldNames: false in a declaration stores them for that collection (true checks it while the config key is off). Restores from the history and drafts are not checked again.

Example: ownership ​

An app where every user keeps their own notes and can share them, a change of someone else is not overwritten, and only server code sets approved:

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

export default defineMongocampCollection({
  name: 'notes',
  schema: z.object({
    text: z.string(),
    sharedWith: z.array(z.string()).default([]),
    approved: z.boolean().optional(),
    metaData: z.object({ tags: z.array(z.string()).optional() }).optional(),
  }),
  validation: 'error',
  timestamps: { createdAt: 'metaData.created', updatedAt: 'metaData.updated', createdBy: 'metaData.createdBy', updatedBy: 'metaData.updatedBy' },
  owner: { read: ({ user }) => ({ $or: [{ 'metaData.createdBy': user.userId }, { sharedWith: user.userId }] }) },
  versioned: { mode: 'timestamp' },
  protectedFields: ['approved'],
})
ts
// server/plugins/notes.ts: rules beyond the behaviours stay before-hooks
import { MongocampError } from '@sfxcode/mongocamp-server-core'
import { definePlugin } from 'nitro'

export default definePlugin((nitroApp) => {
  nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ collectionName, documents }) => {
    if (collectionName === 'notes' && documents.length > 50) {
      throw MongocampError.badRequest('at most 50 notes at once')
    }
  })
})

Hooks in the declaration (3.0) ​

The rules of one collection can live in its declaration, typed by the schema (no Record<string, unknown> casts):

ts
import { MongocampError } from '@sfxcode/mongocamp-server-core'

export default defineMongocampCollection({
  name: 'orders',
  schema: z.object({ customer: z.string().min(1), qty: z.int().min(1) }),
  hooks: {
    beforeInsert(order, { user }) {
      order.customer = order.customer.trim() // order is { customer: string, qty: number, _id?: ObjectId }
      if (order.qty > 100 && !user.roles.includes('wholesale')) {
        throw MongocampError.badRequest('at most 100 at once')
      }
    },
    beforeDelete({ isAdmin }) {
      if (!isAdmin) {
        throw MongocampError.forbidden('orders are kept')
      }
    },
    beforeRead: ({ operation }) => (operation === 'list' ? { status: { $ne: 'archived' } } : undefined),
  },
})
HookGetsMay answer
beforeInsert(document, context)each document (context.source, context.index)a replacement document
beforeReplace(document, context)the new document (context.filter)a replacement document
beforeUpdate(update, context)the update operators (context.filter, context.many)replacement operators
beforeDelete(context)context.filter, context.many—
beforeRead(context)context.filter, context.operationa filter that narrows the read (a scope)

context also has user, isAdmin, collectionName, databaseName, actedBy and session. A hook changes the document in place or answers a new one, refuses the write by throwing, and may be async.

The order of a write: the guard (fields a client may not write are removed) → the hooks of the declaration → the Nitro hooks mongocamp:document:before* → validation → the behaviours (timestamps, owner, tenant, version, soft delete, audit). So a hook sees the input of the schema and can fix it before it is validated; it does not see createdAt or the owner yet. The Nitro hooks stay for rules across collections.

Without the behaviours this needs proxy routes in the app that set the metadata, scope every read, check the owner on every write, compare the update time for lost updates and remove protected fields — with the behaviours the generic API does it. Field visibility per reader (others see only some fields), cascading deletes and replay-safe inserts with client-chosen ids stay app code (before-hooks).

Indexes ​

Since 2.4 the declaration lists the indexes; the server creates them at the start:

ts
export default defineMongocampCollection({
  name: 'orders',
  schema,
  indexes: [
    'status',                                            // { status: 1 }
    '-createdAt',                                        // { createdAt: -1 }
    ['customerId', '-createdAt'],                        // compound
    { fields: { number: 1 }, unique: true },             // with options
    { fields: { title: 'text', notes: 'text' } },        // text index
    { fields: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL: expires at the date of the field
  ],
})

The options of an index are unique, sparse, expireAfterSeconds, partialFilterExpression, collation and name. A collection has at most one text index; a TTL index has one field.

Behaviours add what they need:

  • owner: an index on the owner field, unless an index already starts with it;
  • softDelete: every unique index becomes partial on the documents that are not deleted ({ deletedAt: null }), so a deleted document does not block its value: a new { number: 7 } can be inserted while a deleted one has number 7.

At the start the server compares the declared indexes with the stored ones:

  • it only manages its own indexes: their names start with mongocamp_idx_. Indexes made in the shell, by other services or by POST …/indexes are left alone; they are reported (foreign) in the log;
  • a missing index is created, a changed one is dropped and created again (only the TTL seconds changed: collMod), an own index that is no longer declared is dropped;
  • a failure (duplicate values for a new unique index, no createIndex right) is logged with the collection and the index, and the server starts anyway.

GET …/declaration answers the indexes as the index details show them, and where each one comes from (2.6):

json
"indexes": [
  { "name": "mongocamp_idx_email_1", "key": { "email": 1 }, "unique": true, "sparse": true, "origin": "declaration",
    "partialFilterExpression": { "deletedAt": null }, "partialFilterFrom": "softDelete" },
  { "name": "mongocamp_idx_owner_1", "key": { "owner": 1 }, "unique": false, "sparse": false, "origin": "owner" }
]

origin is declaration or owner (added for the owner behaviour); partialFilterFrom: "softDelete" marks a partial filter that soft delete added to a unique index. expireAfterSeconds is given for TTL indexes.

Building an index on a large collection takes time and load. Declare a new index on a big collection when the load is low, or create it by hand first under its mongocamp_idx_ name.

Relations ​

A reference is a field that holds the _id of a document of another collection. refs names the target collection of each field:

ts
// server/mongocamp/orders.ts
export default defineMongocampCollection({
  name: 'orders',
  schema: z.object({
    customerId: z.instanceof(ObjectId),
    tagIds: z.array(z.instanceof(ObjectId)).default([]),
    total: z.number(),
  }),
  refs: { customerId: 'customers', tagIds: 'tags' },     // 'database:collection' for another database
})

A read with expand replaces the ids by the documents:

ts
const orders = await useMongocampCollection('orders').find({ expand: ['customerId'] })
orders[0].customerId?.name      // typed as the declared customers document | null

The same works on every read route (?expand=customerId&expand=tagIds, or expand=customerId,tagIds), in live updates and in server code.

The rules:

  • Never more than a direct read. The referenced documents are read with the caller's grant and read scope on their collection: owner rules, soft delete and your document:beforeRead hooks apply. A reference the caller cannot read becomes null; in an array it is left out. The answer is still 200.
  • A reference to a document that does not exist is null (left out of an array), a field without a value stays as it is.
  • An array of ids becomes an array of documents in the order of the ids.
  • The password of the users collection is never part of an expansion.
  • At most 5 references per request, only declared ones (400 otherwise, with the names of the declared references). A csv export cannot expand (400), ndjson and json can.
  • Cost: one query per expanded field and page (all ids with $in), not one per document.

Writing back: the client composable sends expanded references as their ids. A replace of a document read with expand is refused when a reference is null or an array, since references you cannot read are not in it; update sends only the fields you change.

Filtering by a reference (2.6). A Lucene term with an id on a declared reference matches the ObjectId (and the same text): customerId:6650f1… finds the orders of that customer in lists, search, count, export, aggregation, many/update, many/delete, live updates and the server collection. -customerId:<id> and OR work; on an array of ids a term matches when one element is the id. Only declared references: on any other field a 24-hex term stays a plain text term.

Both directions in the declaration (2.6). GET …/declaration answers refs with many (whether the field holds an array of ids) and referencedBy, the declared references to this collection, from the declarations of the server:

json
"refs": [{ "field": "customerId", "collection": "customers", "many": false }],
"referencedBy": [{ "collection": "invoices", "database": "shop", "field": "customerId", "many": false }]

many comes from the schema; when the schema cannot tell (no schema of the field, a loose object) declare it: refs: { tagIds: { collection: 'tags', many: true } } (without either it is false). A schema that says otherwise is an error at the start.

What refs does not do: no expansion of the expanded documents (one level), no reverse expansion (the orders of a customer are a find with customerId:<id>), no referential integrity (deleting a customer does not touch its orders — use a before-hook for that). A change of a customer does not send a live event for its orders.

Nested expand (2.10) ​

expand=customerId.companyId also expands the references of the target, at most 3 levels deep (customerId.companyId.countryId). Every level is read with the grants and rules of its own collection; MaxExpands (5) counts the references of all levels. On the client and in server code the first level is typed with the target document, deeper levels as plain objects.

Live updates of referenced documents (2.10) ​

With followRefs (useMongocampLive('orders', { expand: ['customerId'], followRefs: true }), query followRefs=true), a change of a referenced document sends upsert for the documents that refer to it, expanded again. More than 100 send refresh and the client loads again. Off by default; needs a replica set.

Full-text search (2.10) ​

ts
defineMongocampCollection({ name: 'articles', schema, search: { fields: { title: 10, body: 1 }, language: 'english' } })

search manages one text index (mongocamp_idx_search, origin search; a declared text index next to it is refused). Reads take q (?q=pasta, find({ q: 'pasta' }), count too): the words are combined with the filter and the read scope, the best matches first unless sort is given. q on a collection without search answers 400.

Embeddings (3.0) ​

A declaration can keep a vector of text fields up to date, for similarity features and AI tools in your own server code (a built-in vector search with $vectorSearch needs MongoDB Atlas and is not part of the server yet):

ts
export default defineMongocampCollection({
  name: 'articles',
  schema: z.object({ title: z.string(), body: z.string(), tags: z.array(z.string()).default([]) }),
  embedding: {
    from: ['title', 'body', 'tags'], // joined to one text, one field per line
    dimensions: 1536,
    embed: async texts => (await openai.embeddings.create({ model: 'text-embedding-3-small', input: texts })).data.map(entry => entry.embedding),
  },
})
  • After an insert, update or restore the documents go to the job queue: the write answers at once, an embedding service that is down is retried.
  • Only documents whose text changed are embedded (a hash of the text is kept next to the vector); a change of another field costs nothing.
  • The vector (embedding, or field) and its hash (embeddingHash) are system fields: clients cannot write them, and reads do not answer them unless readable: true.
  • mongocamp embed articles (CLI) embeds the documents that were stored before or whose text changed; backfillEmbeddings(server.context, 'articles') does the same in code.
  • Options: field, batchSize (texts per call of embed, default 64), readable. A vector of another length than dimensions fails the job.

Access rules, views, transactions (2.10) ​

See Access Rules (access, fields, tenant), Views and Transactions & Batches.

The MongoDB validator ​

When the declarations are registered, each collection that is not off gets its validator:

  • a missing collection is created with it;
  • an existing one is changed (collMod) only when validator, level or action differ, so the second instance of an application changes nothing;
  • the level is moderate: stored documents that do not match can still be updated;
  • a failure (no collMod right, a view) is logged and the server starts anyway.

The validator belongs to the declaration. Changing it with PATCH …/options works, but the next start replaces it and logs the drift. The validator carries a hash of its content ([mongocamp …] in its description), so a changed declaration is not reported as drift.

Conversion ​

The JSON Schema export of the library (Standard JSON Schema) is converted for MongoDB:

Schema$jsonSchema
integer (z.int())bsonType: ['int', 'long', 'double'], multipleOf: 1
numberbsonType: ['double', 'int', 'long', 'decimal']
date (z.date(), ArkType Date)bsonType: 'date'
ObjectId, Decimal128, Long, Binary instancesbsonType: 'objectId', 'decimal', 'long', 'binData'
constenum
$refinlined (recursive schemas are cut off with a warning)
format, default, examples, ...dropped
other keywords MongoDB does not knowdropped, with a warning naming the field

_id is always allowed, also when the schema allows no other fields.

LibraryValidator
Zod 4converted, dates and BSON classes included
ArkType 2converted, dates and BSON classes included
Valibot 1no JSON Schema export: no MongoDB validator (warning); set validator in the declaration

A validator from existing data ​

GET /mongodb/collections/{name}/schema/validator answers a validator made of a sample of the documents: the types per field, nested objects, array items and the fields that are in every document (requiredThreshold lowers that share, sampleSize and depth as for the schema routes):

ts
const { validator, warnings } = await useMongocampApiCollection('orders').suggestValidator({ requiredThreshold: 0.9 })

The answer can be used as validator of the collection options or of a declaration. It describes the sample: values that the sample did not contain are refused.

Released under the MIT License.