Skip to content

Files ​

GridFS buckets work without any declaration: grants on buckets, GRIDFS_UPLOAD_MAX_BYTES, the routes of System Routes. Since 2.11 a bucket can be declared for limits, types, typed metadata and access rules, files can be shared by signed links, images get variants, and documents reference files. Undeclared buckets behave as before.

Declared buckets ​

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

export default defineMongocampBucket({
  name: 'avatars',
  maxBytes: 2_000_000,
  mimeTypes: ['image/png', 'image/jpeg', 'image/webp'],
  metadata: z.object({ alt: z.string().max(200).optional() }),
  owner: true,
  variants: { widths: [64, 320], formats: ['webp'], presets: { thumb: { w: 64, h: 64, format: 'webp', quality: 70 } } },
  expandLinkSeconds: 3600,
})
OptionEffect
maxBytes413 above it (the smaller of it and GRIDFS_UPLOAD_MAX_BYTES applies)
mimeTypesThe type is read from the content (its first bytes), not the name or header: a renamed .exe is refused with 415 (code 4151). Text formats (text/csv, application/json) are taken from the name when the content is text
metadataA Standard Schema of the metadata; invalid metadata is 400 with its issues, on upload and on PATCH
ownerThe uploader is stored in metadata.owner (or { field }); other users neither list, read, change nor delete the file (administrators do). 3.0: with owner or access, dropping or clearing the bucket and revoking all its links need the administrate right of the bucket, and its .files / .chunks collections are not open to the document routes (only to administrators)
accessAccess rules on the files: read, update, delete answer a boolean or a filter of the files document, create a boolean (it sees filename and metadata)
variantsImage variants clients may ask for (below)
expandLinkSecondsThe lifetime of the signed link that an expand of a file reference adds

A rejected upload is deleted again. A standalone host registers declarations with server.use(buckets([...])). In the client, useMongocampBucket('avatars') types the metadata:

ts
const avatars = useMongocampBucket('avatars')
const { insertedIds } = await avatars.upload(file, { metadata: { alt: 'Me' } })
const src = await avatars.link(insertedIds![0]!, { expiresIn: '1h', variant: { preset: 'thumb' } })

POST /mongodb/buckets/{bucket}/files/{id}/link ({ expiresIn, variant }, read grant and rules) answers { url: '/files/signed/<token>', expiresAt }. The URL downloads the file — or the variant — without authentication until it expires: for <img src>, mails, other services. fileLink(bucket, id, options) answers the absolute URL.

  • The token carries bucket, file id, expiry and variant, signed with HMAC-SHA256 by a key derived from AUTH_SECRET for this purpose only. A changed token answers 403, an expired one 410.
  • expiresIn: seconds or a duration (default 1h), at most FILE_LINK_MAX_DURATION (default 7 days).
  • DELETE /mongodb/buckets/{bucket}/links revokes every link of the bucket at once (a new salt in mc_file_links).
  • Downloads by link are private, without referrer, with a sandboxing Content-Security-Policy; the token is not written to the request log.

A link is a capability: whoever has it can download the file until it expires. Keep lifetimes short.

Image variants ​

GET …/files/{id}/file?w=320&format=webp (or ?preset=thumb) answers a resized copy, for buckets declared with variants. Only the declared widths, heights, formats and presets are allowed (400 otherwise), so clients cannot fill the cache with arbitrary sizes; quality comes from presets. A file that is no image answers 415. 3.0: images above 40 megapixels answer 415, and at most 4 variants render at once per server (more answer 503 with Retry-After: 1; cached variants are always served).

Variants are rendered once by sharp — an optional dependency (npm install sharp; without it 501, code 5013) — stored in the bucket <bucket>.variants and deleted with the file; a small in-memory cache answers repeated requests. sharp ships prebuilt native binaries for the common platforms; check it on your runtime (Node is tested; Bun and Deno load native npm modules with their own caveats). The images of the standalone server do not include it — add it to an image of your own.

File references ​

ts
export default defineMongocampCollection({
  name: 'people',
  schema: z.object({ name: z.string(), avatarId: z.instanceof(ObjectId).optional() }),
  refs: { avatarId: { bucket: 'avatars', onDelete: 'delete-file' } },
  validateRefs: true,
})
  • validateRefs: a write whose file does not exist is refused (400).
  • expand=avatarId answers the file information (_id, filename, length, uploadDate, metadata) — typed as ExpandedFile — and a signed link when the bucket declares expandLinkSeconds. The bucket grant and rules of the caller apply: a file the caller cannot read becomes null.
  • onDelete: 'delete-file' deletes the file when the document is deleted. A soft delete keeps it; documents that the purge index of softDelete removes (MongoDB itself, without an event) keep their files too.
  • GET /mongodb/buckets/{bucket} lists the referring collections in referencedBy.

Released under the MIT License.