Create

The insert() and insertBulk() functions let you add documents into a collection.

🔹 insert()

Adds a single document to one collection.

Maps to POST /:collection/docs on the API. The server validates the payload against your collection schema and enforces uniqueness constraints. On success the API returns the created document with `_id`, `createdAt`, and `updatedAt`.

await db.users.insert({
  name: "Dinesh Chugtai",
  email: "dinesh@piedpiper.com",
  isAdmin: false,
});

Behavior:

  • Validates the payload against your schema.
  • Applies default values if you skipped them.
  • Throws if required fields are missing or uniqueness is violated.

🔸 insertBulk()

Inserts multiple documents at once.

Maps to POST /:collection/bulk. The response returns per-batch status fields: inserted, failed,documents, and optional errors.

await db.users.insertBulk([
  { name: "Jared Dunn", email: "jared@piedpiper.com", isAdmin: false },
  { name: "Erlich Bachman", email: "erlich@piedpiper.com", isAdmin: true },
]);

Notes:

  • If any doc violates schema or uniqueness, the entire batch fails.
  • Same rules apply: default values, validation, etc.

Bulk inserts are currently partial success, not all-or-nothing atomic. Valid documents can be inserted while invalid ones are returned in errors.

✅ Key Management

You can pass a custom key:

await db.users.insert({
  key: "custom_id",
  name: "Monica Hall",
  isAdmin: true,
});

Otherwise, PaperDB generates a nanoid for you.

Error Responses

The API returns structured JSON errors. Common cases:

// 400 — schema validation failed
{ "error": "Field 'email' is required" }

// 409 — unique constraint violated
{ "error": "Unique field violation — 'email' already exists in this collection." }

// 401 — missing or invalid API key
{ "error": "Missing or invalid Authorization header" }

// 429 — quota exceeded
{
  "error": "Monthly API request limit reached (1,000 requests). Upgrade your plan for more.",
  "code": "QUOTA_EXCEEDED",
  "limit": 1000,
  "current": 1001,
  "plan": "free",
  "upgradeUrl": "https://paperdb.app/pricing"
}

// 429 — rate limit exceeded
{
  "error": "Rate limit exceeded. Please slow down.",
  "retryAfter": 42
}