11. Migrations & files
The shop grows. Two things come up that declarations cannot do: a change of the stored data, and pictures of the customers.
A migration
Customers created before step 6 may have emails with capitals. A migration fixes the stored data once per database:
// step 11: a data change that runs once per database — emails stored before step 6 may have capitals
export default defineMongocampMigration({
description: 'store the emails of the customers in lower case',
async up({ db }) {
await db.collection('customers').updateMany({ email: { $regex: '[A-Z]' } }, [{ $set: { email: { $toLower: '$email' } } }])
},
})The file name is the id; the ids decide the order. The server applies pending migrations at the start, before the first request, and records them in mc_migrations — a restart runs nothing again. With several instances one of them runs them, the others wait. mongocamp migrate status shows the state; Migrations & Seeds has the details, seeds for demo data included.
Avatars
A declared bucket limits what can be uploaded and who sees it:
import { z } from 'zod'
// step 11: pictures of the customers — small images only, each user sees the files they uploaded
export default defineMongocampBucket({
name: 'avatars',
maxBytes: 500_000,
mimeTypes: ['image/png', 'image/jpeg', 'image/webp'],
metadata: z.object({ alt: z.string().max(100).optional() }),
owner: true,
})The role of the shop gets the bucket grant in nuxt.config.ts (grantType: 'BUCKET'). Then in a page:
const avatars = useMongocampBucket('avatars')
const { insertedIds } = await avatars.upload(file, { metadata: { alt: 'Ann' } })
// a URL for <img src>: signed, valid for an hour, no token needed
const src = await avatars.link(insertedIds![0]!, { expiresIn: '1h' })The type is checked from the content of the file, not its name: a renamed program is refused with 415. A larger file is refused with 413, invalid metadata with 400. Image variants (resized copies) and file references in documents are in Files.
