4. Behaviours
Orders need more than a schema: who placed it and when, that only its owner sees it, that a delete can be undone, that two tabs do not overwrite each other, and a history. With MongoCamp each of these is one flag in the declaration, and the generic API enforces it. You write no routes.
import { ObjectId } from 'mongodb'
import { z } from 'zod'
export default defineMongocampCollection({
name: 'orders',
schema: z.object({
customerId: z.instanceof(ObjectId),
items: z.array(z.object({
product: z.string().min(1),
qty: z.int().min(1),
price: z.number().min(0),
})).min(1),
// computed by a before-hook (step 5)
total: z.number().min(0).optional(),
status: z.enum(['open', 'paid', 'shipped']).default('open'),
}),
validation: 'error',
// step 4: behaviours
timestamps: { createdBy: true }, // createdAt, updatedAt and the user who created the order
owner: true, // the owner is createdBy: every user sees and changes only the own orders
softDelete: true, // a delete sets deletedAt, restore brings the order back
versioned: true, // _v: a write based on an outdated order answers 409
audit: true, // the history of every order
protectedFields: ['total'], // clients cannot write it, the before-hook does
// step 6: the lists the app shows
indexes: ['status', ['customerId', '-createdAt']],
// step 7: customerId refers to a customer
refs: { customerId: 'customers' },
})The fields the behaviours write are not in the schema. They are added to the document type, to the MongoDB validator, and to the fields clients cannot write. An order you read is typed with createdAt: Date, createdBy: string, _v: number and the optional deletedAt.
timestamps
createdAt and updatedAt on every write; createdBy: true adds the user of the request. The values are written by the server: a createdAt sent by a client is ignored. Use an object to rename them or nest them ({ createdAt: 'meta.created' }).
owner
The creator owns the order. Reads, counts and live updates of others leave it out, and their updates and deletes answer 404, as if it did not exist. The owner field is the createdBy of timestamps. owner: { read: 'all' } lets everyone with the read grant see all orders while only the owner changes them. A function decides per user (shared documents).
versioned
Every write increases _v. The typed composable sends the _v of the document you read, so a change based on an outdated copy answers 409 with the stored document:
async function markPaid(order: Order) {
notice.value = ''
try {
// the version of the order that was read goes along: someone else's change in between answers 409
await orders.update(order, { status: 'paid' })
}
catch (error) {
const failure = error as MongocampRequestError
notice.value = failure.isConflict ? `changed in the meantime, now: ${failure.current?.status}` : failure.message
}
}Pass { retryOnConflict: true } to update to apply your change to the stored version instead.
softDelete
remove sets deletedAt. The order disappears from every read, and restore brings it back:
const deleted = ref<Order[]>([])
async function remove(order: Order) {
await orders.remove(order) // sets deletedAt, the order leaves every list
deleted.value.push(order)
}
async function restore(order: Order) {
await orders.restore(order)
deleted.value = deleted.value.filter(entry => entry !== order)
}Administrators of the collection read deleted orders with withDeleted: true. softDelete: { purgeAfterDays: 30 } removes them for good later.
audit
Every write leaves a record with the user, the time, and the document before and after:
const history = ref<Array<{ operation: string, user: string, at: Date }>>([])
async function showHistory(order: Order) {
history.value = await orders.history(order)
}For an order that was created, paid, changed, deleted and restored, history answers restore, softDelete, update, update, insert, newest first.
protectedFields
total is protected: clients cannot write it, and a total they send is dropped. The next step computes it on the server.
All behaviours and their options: Declared collections.
