Skip to content
VibORM
Esc
↑↓navigate↵open⌘Jpreview
On this page

Quick Start

Build your first VibORM schema in 5 minutes with a simple blog example featuring users and posts

1. Set Up the Project

Start from an empty directory. This guide uses SQLite through better-sqlite3, so it needs no database server:

mkdir blog && cd blog
npm init -y
npm pkg set type=module
npm install viborm better-sqlite3
npm install -D typescript tsx @types/node @types/better-sqlite3

type=module makes your files ES modules, which the top-level await in step 5 needs. tsx runs TypeScript files on Node.js. For another database, install its driver instead of better-sqlite3 (see Installation).

Add a tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "skipLibCheck": true,
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}

Relative imports name their .ts file (./schema.ts), so the same files run under tsx and under Node.js’s own type stripping.

2. Define Your Schema

Create a schema.ts file with your model definitions:

import { s } from "viborm";

// User model
export const user = s.model({
  id: s.string().id().ulid(),
  email: s.string().unique(),
  name: s.string(),
  createdAt: s.dateTime().default(() => new Date()),
  posts: s.toMany(() => post),
});

// Post model
export const post = s.model({
  id: s.string().id().ulid(),
  title: s.string(),
  content: s.string().nullable(),
  published: s.boolean().default(false),
  authorId: s.string(),
  author: s.toOne(() => user)
    .fields("authorId")
    .references("id"),
  createdAt: s.dateTime().default(() => new Date()),
});

3. Create the Client

Initialize your database client with your preferred database:

import { createClient } from "viborm/sqlite3";
import * as schema from "./schema.ts";

export const client = createClient({
  schema,
  dataDir: "./data.db",
});
import { createClient } from "viborm/postgres";
import * as schema from "./schema.ts";

export const client = createClient({
  schema,
  databaseUrl: process.env.DATABASE_URL,
});
import { createClient } from "viborm/pg";
import * as schema from "./schema.ts";

export const client = createClient({
  schema,
  databaseUrl: process.env.DATABASE_URL,
});
import { createClient } from "viborm/pglite";
import * as schema from "./schema.ts";

export const client = createClient({
  schema,
  dataDir: "./data",
});

4. Create the Database Tables

Your database is still empty. Create a viborm.config.ts in your project root and push the schema:

import { defineConfig } from "viborm/config";
import { client } from "./src/db/client.ts";

export default defineConfig({ client });

The CLI includes a TypeScript loader and reads the project .env. Run it with Node.js so a native Node driver such as better-sqlite3 uses its supported runtime:

npx viborm push

With pnpm, use pnpm exec viborm push. The CLI does not need tsx. Use the Bun SQLite driver when the application itself runs on Bun.

push syncs your models straight to the database without migration files — see Push for details and Configuration for config options.

5. Query Your Data

Now you can use the fully typed client:

import { client } from "./db/client.ts";

// Create a user
const newUser = await client.user.create({
  data: {
    email: "alice@example.com",
    name: "Alice",
  },
});

// Create a post for the user
const newPost = await client.post.create({
  data: {
    title: "My First Post",
    content: "Hello, VibORM!",
    authorId: newUser.id,
  },
});

// Find users with their posts
const users = await client.user.findMany({
  where: {
    email: { contains: "@example.com" },
  },
  include: {
    posts: {
      where: { published: true },
      orderBy: { createdAt: "desc" },
    },
  },
});

// Update a post
await client.post.update({
  where: { id: newPost.id },
  data: { published: true },
});

// Delete unpublished posts
await client.post.deleteMany({
  where: { published: false },
});

console.log(users);

Type-check the project, then run the file:

npx tsc
npx tsx src/index.ts

6. Type Safety in Action

VibORM provides full type inference:

// ✅ TypeScript knows the exact shape
const user = await client.user.findUnique({
  where: { email: "alice@example.com" },
  select: { id: true, name: true },
});
// Type: { id: string; name: string } | null

// ❌ TypeScript catches errors at compile time
await client.user.create({
  data: {
    email: "bob@example.com",
    // Error: 'name' is required
  },
});

// ❌ Invalid field names are rejected
await client.user.findMany({
  where: { invalidField: "value" }, // Error: 'invalidField' does not exist
});

The types reject a misspelled key, even beside a correct one, at the top level of every argument. They also reject one inside nested write data (create, createMany, connectOrCreate, update, upsert), inside a nested select or include and its where, inside an operator object of a top-level where field ({ contains: "x", mdoe: "insensitive" }), and in a groupBy orderBy field that is not in by.

Some misuse still type-checks:

  • an operator typo below a top-level where field: inside a relation filter, an AND / OR / NOT group, or a nested include / select where;
  • a misspelled key below a where key that is optional in the value’s type, in a where object that also spreads a value typed as the full where payload ({ ...filter, ...(ok ? { author: { email, emial } } : {}) });
  • a misspelled relation operation (conect), or a misspelled key in a nested selector (connect, or the where of a nested update, delete or upsert), in cursor or in having;
  • a typo inside a polymorphic relation’s variant;
  • a typo in an aggregate selector, and _min / _max on a boolean;
  • a foreign key written beside its relation’s connect;
  • groupBy with an empty by, and select: {} on a bulk write.

A type parameter that stands for a whole nested write object, a whole operator object, a relation filter or a nested include / select where is rejected, because its keys cannot be checked. Write the object out at the call site, or give it the payload type. A groupBy orderBy value whose type names a field outside by is rejected even when that key is optional: narrow its type to the grouped fields and aggregates.

VibORM also validates every call at runtime, before any SQL runs. Input that the types let through but the schema does not admit is rejected with a ValidationError (code V4001). The message names the path, such as data.posts.create.

Next Steps

Was this page helpful?