Skip to main content

CRUD Operations

Basic create, read, update, and delete operations.

Insert​

const doc = await collection.insert({
name: 'Alice',
role: 'admin',
})
  • ID is auto-generated if not provided
  • Defaults are applied for fields with .default()
  • Validates the document against the schema

Bulk Insert​

const docs = await collection.insertMany([
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' },
{ name: 'Charlie', role: 'user' },
])

All documents are validated before any are inserted.

Find​

// All documents
const all = await collection.find()

// With filter
const admins = await collection.find({ role: 'admin' })

// Pagination
const page2 = await collection
.query()
.page(2, 20)
.find()

first()​

Returns the first matching document or null:

const user = await collection.first({ id: 'abc-123' })
if (user) {
console.log(user.name)
}

firstOrFail()​

Returns the first matching document or throws NotFoundError:

const user = await collection.firstOrFail({ id: 'abc-123' })
// Throws if not found

Update​

// Update by filter
const count = await collection.update(
{ id: 'abc-123' },
{ name: 'Alice Updated' }
)
console.log(`Updated ${count} document(s)`)

Bulk Update​

// Update ALL documents
const count = await collection.updateAll({ role: 'guest' })

Delete​

// Delete by filter
const count = await collection.delete({ id: 'abc-123' })

// Delete ALL documents
const count = await collection.deleteAll()

Batch Operations​

For efficient bulk operations:

// Bulk insert
await collection.insertMany([...])

// Bulk update (all docs)
await collection.updateAll({ status: 'archived' })

// Bulk delete (all docs)
await collection.deleteAll()

Error Handling​

import { ValidationError, DuplicateError, NotFoundError } from '@sajjadbzn/jcell'

try {
await collection.insert({ name: 42 } as any)
} catch (err) {
if (err instanceof ValidationError) {
console.error('Validation failed:', err.message)
} else if (err instanceof DuplicateError) {
console.error('Duplicate ID:', err.message)
} else if (err instanceof NotFoundError) {
console.error('Not found:', err.message)
}
}

Complete CRUD Example​

import { createDB, schema, t, memoryAdapter } from '@sajjadbzn/jcell'

const userSchema = schema({
id: t.id(),
name: t.string(),
email: t.string(),
role: t.enum(['admin', 'user'] as const),
})

const db = createDB({ adapter: memoryAdapter() })
const users = db.collection('users', userSchema)

// Create
const alice = await users.insert({
name: 'Alice',
email: 'alice@example.com',
role: 'admin',
})

// Read
const all = await users.find()
const found = await users.first({ email: 'alice@example.com' })

// Update
await users.update({ id: alice.id }, { role: 'user' })

// Delete
await users.delete({ id: alice.id })

console.log('All operations completed ✅')