CollectionImpl

类:CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>

定义于: packages/db/src/collection.ts:204

继承自

类型参数

T extends object = Record<string, unknown>

TKey extends string | number = string | number

TUtils extends UtilsRecord = {}

TSchema extends StandardSchemaV1 = StandardSchemaV1

TInsertInput extends object = T

构造函数

new CollectionImpl()

ts
new CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>(config): CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>
new CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>(config): CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>

定义于: packages/db/src/collection.ts:407

创建一个新的 Collection 实例

参数

config

CollectionConfig<T, TKey, TSchema, TInsertInput>

集合的配置对象

Returns (返回)

CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>

Throws

如果同步配置丢失,则抛出错误

属性

config

ts
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;

定义于: packages/db/src/collection.ts:211


id

ts
id: string;
id: string;

定义于: packages/db/src/collection.ts:331


optimisticDeletes

ts
optimisticDeletes: Set<TKey>;
optimisticDeletes: Set<TKey>;

定义于: packages/db/src/collection.ts:221


optimisticUpserts

ts
optimisticUpserts: Map<TKey, T>;
optimisticUpserts: Map<TKey, T>;

定义于: packages/db/src/collection.ts:220


pendingSyncedTransactions

ts
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];

定义于: packages/db/src/collection.ts:215


syncedData

ts
syncedData: Map<TKey, T> | SortedMap<TKey, T>;
syncedData: Map<TKey, T> | SortedMap<TKey, T>;

定义于: packages/db/src/collection.ts:216


syncedMetadata

ts
syncedMetadata: Map<TKey, unknown>;
syncedMetadata: Map<TKey, unknown>;

定义于: packages/db/src/collection.ts:217


transactions

ts
transactions: SortedMap<string, Transaction<any>>;
transactions: SortedMap<string, Transaction<any>>;

定义于: packages/db/src/collection.ts:214


utils

ts
utils: Record<string, Fn> = {};
utils: Record<string, Fn> = {};

定义于: packages/db/src/collection.ts:238

访问器

indexes

Get Signature

ts
get indexes(): Map<number, BaseIndex<TKey>>
get indexes(): Map<number, BaseIndex<TKey>>

定义于: packages/db/src/collection.ts:1439

获取用于查询优化的已解析索引

Returns (返回)

Map<number, BaseIndex<TKey>>


size

Get Signature

ts
get size(): number
get size(): number

定义于: packages/db/src/collection.ts:995

获取集合的当前大小 (缓存)

Returns (返回)

number


state

Get Signature

ts
get state(): Map<TKey, T>
get state(): Map<TKey, T>

定义于: packages/db/src/collection.ts:2038

将集合的当前状态作为 Map 获取

示例
ts
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)

for (const [key, item] of itemsMap) {
  console.log(`${key}: ${item.title}`)
}

// Check if specific item exists
if (itemsMap.has("todo-1")) {
  console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)

for (const [key, item] of itemsMap) {
  console.log(`${key}: ${item.title}`)
}

// Check if specific item exists
if (itemsMap.has("todo-1")) {
  console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}
Returns (返回)

Map<TKey, T>

包含集合中所有项目的 Map,键是标识符


status

Get Signature

ts
get status(): CollectionStatus
get status(): CollectionStatus

定义于: packages/db/src/collection.ts:336

获取集合的当前状态

Returns (返回)

CollectionStatus


toArray

Get Signature

ts
get toArray(): T[]
get toArray(): T[]

定义于: packages/db/src/collection.ts:2071

将集合的当前状态作为 Array 获取

Returns (返回)

T[]

包含集合中所有项目的 Array

方法

[iterator]()

ts
iterator: IterableIterator<[TKey, T]>
iterator: IterableIterator<[TKey, T]>

定义于: packages/db/src/collection.ts:1046

获取所有条目 (虚拟派生状态)

Returns (返回)

IterableIterator<[TKey, T]>


cleanup()

ts
cleanup(): Promise<void>
cleanup(): Promise<void>

定义于: packages/db/src/collection.ts:583

通过停止同步和清除数据来清理集合。可以手动调用,也可以由垃圾回收自动调用。

Returns (返回)

Promise<void>


commitPendingTransactions()

ts
commitPendingTransactions(): void
commitPendingTransactions(): void

定义于: packages/db/src/collection.ts:1082

如果当前没有活动事务,则尝试提交挂起的同步事务。此方法处理来自挂起事务的操作,并将它们应用于同步数据。

Returns (返回)

void


createIndex()

ts
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>

定义于: packages/db/src/collection.ts:1344

在集合上创建索引以加快查询速度。索引通过允许二分搜索和范围查询而不是完整扫描来显著提高查询性能。

类型参数

TResolver extends IndexResolver<TKey> = typeof BTreeIndex

索引解析器的类型(构造函数或异步加载器)

参数

indexCallback

(row) => any

从每个项目提取索引值的函数

config

IndexOptions<TResolver> = {}

配置,包括索引类型和特定于类型的选项

Returns (返回)

IndexProxy<TKey>

提供索引可用时访问索引的代理

示例

ts
// Create a default B+ tree index
const ageIndex = collection.createIndex((row) => row.age)

// Create a ordered index with custom options
const ageIndex = collection.createIndex((row) => row.age, {
  indexType: BTreeIndex,
  options: { compareFn: customComparator },
  name: 'age_btree'
})

// Create an async-loaded index
const textIndex = collection.createIndex((row) => row.content, {
  indexType: async () => {
    const { FullTextIndex } = await import('./indexes/fulltext.js')
    return FullTextIndex
  },
  options: { language: 'en' }
})
// Create a default B+ tree index
const ageIndex = collection.createIndex((row) => row.age)

// Create a ordered index with custom options
const ageIndex = collection.createIndex((row) => row.age, {
  indexType: BTreeIndex,
  options: { compareFn: customComparator },
  name: 'age_btree'
})

// Create an async-loaded index
const textIndex = collection.createIndex((row) => row.content, {
  indexType: async () => {
    const { FullTextIndex } = await import('./indexes/fulltext.js')
    return FullTextIndex
  },
  options: { language: 'en' }
})

currentStateAsChanges()

ts
currentStateAsChanges(options): ChangeMessage<T, string | number>[]
currentStateAsChanges(options): ChangeMessage<T, string | number>[]

定义于: packages/db/src/collection.ts:2113

将集合的当前状态作为更改数组返回

参数

options

CurrentStateAsChangesOptions<T> = {}

选项,包括可选的 where 过滤器

Returns (返回)

ChangeMessage<T, string | number>[]

更改数组

示例

ts
// Get all items as changes
const allChanges = collection.currentStateAsChanges()

// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
  where: (row) => row.status === 'active'
})

// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
  whereExpression: eq(row.status, 'active')
})
// Get all items as changes
const allChanges = collection.currentStateAsChanges()

// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
  where: (row) => row.status === 'active'
})

// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
  whereExpression: eq(row.status, 'active')
})

delete()

ts
delete(keys, config?): Transaction<any>
delete(keys, config?): Transaction<any>

定义于: packages/db/src/collection.ts:1939

从集合中删除一个或多个项目

参数

keys

要删除的单个键或键数组

TKey | TKey[]

config?

OperationConfig

可选配置,包括元数据

Returns (返回)

Transaction<any>

代表删除操作的 Transaction 对象

示例

ts
// Delete a single item
const tx = collection.delete("todo-1")
await tx.isPersisted.promise
// Delete a single item
const tx = collection.delete("todo-1")
await tx.isPersisted.promise
ts
// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.isPersisted.promise
// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.isPersisted.promise
ts
// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.isPersisted.promise
// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.delete("item-1")
  await tx.isPersisted.promise
  console.log('Delete successful')
} catch (error) {
  console.log('Delete failed:', error)
}
// Handle errors
try {
  const tx = collection.delete("item-1")
  await tx.isPersisted.promise
  console.log('Delete successful')
} catch (error) {
  console.log('Delete failed:', error)
}

entries()

ts
entries(): IterableIterator<[TKey, T]>
entries(): IterableIterator<[TKey, T]>

定义于: packages/db/src/collection.ts:1034

获取所有条目 (虚拟派生状态)

Returns (返回)

IterableIterator<[TKey, T]>


forEach()

ts
forEach(callbackfn): void
forEach(callbackfn): void

定义于: packages/db/src/collection.ts:1055

为集合中的每个条目执行一个回调函数

参数

callbackfn

(value, key, index) => void

Returns (返回)

void


generateGlobalKey()

ts
generateGlobalKey(key, item): string
generateGlobalKey(key, item): string

定义于: packages/db/src/collection.ts:1306

参数

key

any

item

any

Returns (返回)

string


get()

ts
get(key): undefined | T
get(key): undefined | T

定义于: packages/db/src/collection.ts:959

获取键的当前值 (虚拟派生状态)

参数

key

TKey

Returns (返回)

undefined | T


getKeyFromItem()

ts
getKeyFromItem(item): TKey
getKeyFromItem(item): TKey

定义于: packages/db/src/collection.ts:1302

参数

item

T

Returns (返回)

TKey


has()

ts
has(key): boolean
has(key): boolean

定义于: packages/db/src/collection.ts:977

检查集合中是否存在某个键 (虚拟派生状态)

参数

key

TKey

Returns (返回)

boolean


insert()

ts
insert(data, config?): 
  | Transaction<Record<string, unknown>>
| Transaction<T>
insert(data, config?): 
  | Transaction<Record<string, unknown>>
| Transaction<T>

定义于: packages/db/src/collection.ts:1594

将一个或多个项目插入到集合中

参数

data

TInsertInput | TInsertInput[]

config?

InsertConfig

可选配置,包括元数据

Returns (返回)

| Transaction<Record<string, unknown>> | Transaction<T>

代表插入操作的 Transaction 对象

Throws

如果数据通过模式验证失败

示例

ts
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.isPersisted.promise
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.isPersisted.promise
ts
// Insert multiple todos at once
const tx = collection.insert([
  { id: "1", text: "Buy milk", completed: false },
  { id: "2", text: "Walk dog", completed: true }
])
await tx.isPersisted.promise
// Insert multiple todos at once
const tx = collection.insert([
  { id: "1", text: "Buy milk", completed: false },
  { id: "2", text: "Walk dog", completed: true }
])
await tx.isPersisted.promise
ts
// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
  { metadata: { source: "mobile-app" } }
)
await tx.isPersisted.promise
// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
  { metadata: { source: "mobile-app" } }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.insert({ id: "1", text: "New item" })
  await tx.isPersisted.promise
  console.log('Insert successful')
} catch (error) {
  console.log('Insert failed:', error)
}
// Handle errors
try {
  const tx = collection.insert({ id: "1", text: "New item" })
  await tx.isPersisted.promise
  console.log('Insert successful')
} catch (error) {
  console.log('Insert failed:', error)
}

isReady()

ts
isReady(): boolean
isReady(): boolean

定义于: packages/db/src/collection.ts:294

检查集合是否已准备好使用。如果集合已被其同步实现标记为就绪,则返回 true。

Returns (返回)

boolean

如果集合已准备好,则为 true,否则为 false

示例

ts
if (collection.isReady()) {
  console.log('Collection is ready, data is available')
  // Safe to access collection.state
} else {
  console.log('Collection is still loading')
}
if (collection.isReady()) {
  console.log('Collection is ready, data is available')
  // Safe to access collection.state
} else {
  console.log('Collection is still loading')
}

keys()

ts
keys(): IterableIterator<TKey>
keys(): IterableIterator<TKey>

定义于: packages/db/src/collection.ts:1002

获取所有键 (虚拟派生状态)

Returns (返回)

IterableIterator<TKey>


map()

ts
map<U>(callbackfn): U[]
map<U>(callbackfn): U[]

定义于: packages/db/src/collection.ts:1067

通过对集合中的每个条目调用函数来创建结果的新数组

类型参数

U

参数

callbackfn

(value, key, index) => U

Returns (返回)

U[]


onFirstReady()

ts
onFirstReady(callback): void
onFirstReady(callback): void

定义于: packages/db/src/collection.ts:272

注册一个回调函数,当集合首次准备好时执行。用于预加载集合。

参数

callback

() => void

集合首次准备好时调用的函数

Returns (返回)

void

示例

ts
collection.onFirstReady(() => {
  console.log('Collection is ready for the first time')
  // Safe to access collection.state now
})
collection.onFirstReady(() => {
  console.log('Collection is ready for the first time')
  // Safe to access collection.state now
})

onTransactionStateChange()

ts
onTransactionStateChange(): void
onTransactionStateChange(): void

定义于: packages/db/src/collection.ts:2271

当事务发生变化时触发重新计算。 Transaction 类应调用此方法来更新状态。

Returns (返回)

void


preload()

ts
preload(): Promise<void>
preload(): Promise<void>

定义于: packages/db/src/collection.ts:544

预加载集合数据,如果尚未启动则启动同步。多个并发调用将共享同一个 Promise。

Returns (返回)

Promise<void>


startSyncImmediate()

ts
startSyncImmediate(): void
startSyncImmediate(): void

定义于: packages/db/src/collection.ts:450

立即启动同步 - 编译查询的内部方法。此方法绕过懒加载,用于实时查询结果等特殊情况。

Returns (返回)

void


stateWhenReady()

ts
stateWhenReady(): Promise<Map<TKey, T>>
stateWhenReady(): Promise<Map<TKey, T>>

定义于: packages/db/src/collection.ts:2052

将集合的当前状态作为 Map 获取,但仅在数据可用时解析。在解析之前等待第一次同步提交完成。

Returns (返回)

Promise<Map<TKey, T>>

解析为包含集合中所有项目的 Map 的 Promise


subscribeChanges()

ts
subscribeChanges(callback, options): () => void
subscribeChanges(callback, options): () => void

定义于: packages/db/src/collection.ts:2158

订阅集合中的更改

参数

callback

(changes) => void

项目更改时调用的函数

options

SubscribeChangesOptions<T> = {}

订阅选项,包括 includeInitialState 和 where 过滤器

Returns (返回)

Function

退订函数 - 调用此函数可停止监听更改

Returns (返回)

void

示例

ts
// Basic subscription
const unsubscribe = collection.subscribeChanges((changes) => {
  changes.forEach(change => {
    console.log(`${change.type}: ${change.key}`, change.value)
  })
})

// Later: unsubscribe()
// Basic subscription
const unsubscribe = collection.subscribeChanges((changes) => {
  changes.forEach(change => {
    console.log(`${change.type}: ${change.key}`, change.value)
  })
})

// Later: unsubscribe()
ts
// Include current state immediately
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, { includeInitialState: true })
// Include current state immediately
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, { includeInitialState: true })
ts
// Subscribe only to changes matching a condition
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  where: (row) => row.status === 'active'
})
// Subscribe only to changes matching a condition
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  where: (row) => row.status === 'active'
})
ts
// Subscribe using a pre-compiled expression
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  whereExpression: eq(row.status, 'active')
})
// Subscribe using a pre-compiled expression
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  whereExpression: eq(row.status, 'active')
})

subscribeChangesKey()

ts
subscribeChangesKey(
   key, 
   listener, 
   __namedParameters): () => void
subscribeChangesKey(
   key, 
   listener, 
   __namedParameters): () => void

定义于: packages/db/src/collection.ts:2197

订阅特定键的更改

参数

key

TKey

listener

ChangeListener<T, TKey>

__namedParameters
includeInitialState?

boolean = false

Returns (返回)

Function

Returns (返回)

void


toArrayWhenReady()

ts
toArrayWhenReady(): Promise<T[]>
toArrayWhenReady(): Promise<T[]>

定义于: packages/db/src/collection.ts:2081

将集合的当前状态作为 Array 获取,但仅在数据可用时解析。在解析之前等待第一次同步提交完成。

Returns (返回)

Promise<T[]>

解析为包含集合中所有项目的 Array 的 Promise


update()

Call Signature

ts
update<TItem>(key, callback): Transaction
update<TItem>(key, callback): Transaction

定义于: packages/db/src/collection.ts:1725

使用回调函数更新集合中的一个或多个项目

类型参数

TItem extends object = T

Parameters
key

unknown[]

callback

(drafts) => void

Returns (返回)

Transaction

代表更新操作的 Transaction 对象

Throws

如果更新的数据通过模式验证失败

示例
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

调用签名

ts
update<TItem>(
   keys, 
   config, 
   callback): Transaction
update<TItem>(
   keys, 
   config, 
   callback): Transaction

定义于: packages/db/src/collection.ts:1731

使用回调函数更新集合中的一个或多个项目

类型参数

TItem extends object = T

Parameters
keys

unknown[]

要更新的单个键或键数组

config

OperationConfig

callback

(drafts) => void

Returns (返回)

Transaction

代表更新操作的 Transaction 对象

Throws

如果更新的数据通过模式验证失败

示例
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

调用签名

ts
update<TItem>(id, callback): Transaction
update<TItem>(id, callback): Transaction

定义于: packages/db/src/collection.ts:1738

使用回调函数更新集合中的一个或多个项目

类型参数

TItem extends object = T

Parameters
id

unknown

callback

(draft) => void

Returns (返回)

Transaction

代表更新操作的 Transaction 对象

Throws

如果更新的数据通过模式验证失败

示例
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

调用签名

ts
update<TItem>(
   id, 
   config, 
   callback): Transaction
update<TItem>(
   id, 
   config, 
   callback): Transaction

定义于: packages/db/src/collection.ts:1744

使用回调函数更新集合中的一个或多个项目

类型参数

TItem extends object = T

Parameters
id

unknown

config

OperationConfig

callback

(draft) => void

Returns (返回)

Transaction

代表更新操作的 Transaction 对象

Throws

如果更新的数据通过模式验证失败

示例
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

values()

ts
values(): IterableIterator<T>
values(): IterableIterator<T>

定义于: packages/db/src/collection.ts:1022

获取所有值 (虚拟派生状态)

Returns (返回)

IterableIterator<T>

我们的合作伙伴
Code Rabbit
Electric
Prisma
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。