集合

Interface: Collection<T, TKey, TUtils, TSchema, TInsertInput>

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

增强的 Collection 接口,包含数据类型 T 和工具类型 TUtils

继承自

类型参数

T extends object = Record<string, unknown>

集合中项目的类型

TKey extends string | number = string | number

集合键的类型

TUtils extends UtilsRecord = {}

工具记录的类型

TSchema extends StandardSchemaV1 = StandardSchemaV1

TInsertInput extends object = T

插入操作的类型(对于具有默认值的模式,可以与 T 不同)

属性

config

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

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

继承自

CollectionImpl.config


id

ts
id: string;
id: string;

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

继承自

CollectionImpl.id


optimisticDeletes

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

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

继承自

CollectionImpl.optimisticDeletes


optimisticUpserts

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

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

继承自

CollectionImpl.optimisticUpserts


pendingSyncedTransactions

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

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

继承自

CollectionImpl.pendingSyncedTransactions


syncedData

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

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

继承自

CollectionImpl.syncedData


syncedMetadata

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

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

继承自

CollectionImpl.syncedMetadata


transactions

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

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

继承自

CollectionImpl.transactions


utils

ts
readonly utils: TUtils;
readonly utils: TUtils;

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

Overrides

CollectionImpl.utils

访问器

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>>

继承自

CollectionImpl.indexes


size

Get Signature

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

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

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

Returns (返回)

number

继承自

CollectionImpl.size


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,键为标识符

继承自

CollectionImpl.state


status

Get Signature

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

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

获取集合的当前状态

Returns (返回)

CollectionStatus

继承自

CollectionImpl.status


toArray

Get Signature

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

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

以 Array 的形式获取集合的当前状态

Returns (返回)

T[]

包含集合中所有项目的 Array

继承自

CollectionImpl.toArray

方法

[iterator]()

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

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

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

Returns (返回)

IterableIterator<[TKey, T]>

继承自

CollectionImpl.[iterator]


cleanup()

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

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

清理集合,停止同步并清除数据。此方法可手动调用,也可由垃圾回收自动调用。

Returns (返回)

Promise<void>

继承自

CollectionImpl.cleanup


commitPendingTransactions()

ts
commitPendingTransactions(): void
commitPendingTransactions(): void

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

尝试提交待处理的同步事务(如果没有活动事务)。此方法处理待处理事务中的操作,并将它们应用于同步数据。

Returns (返回)

void

继承自

CollectionImpl.commitPendingTransactions


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' }
})

继承自

CollectionImpl.createIndex


currentStateAsChanges()

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

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

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

Parameters

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')
})

继承自

CollectionImpl.currentStateAsChanges


delete()

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

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

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

Parameters

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)
}

继承自

CollectionImpl.delete


entries()

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

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

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

Returns (返回)

IterableIterator<[TKey, T]>

继承自

CollectionImpl.entries


forEach()

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

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

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

Parameters

callbackfn

(value, key, index) => void

Returns (返回)

void

继承自

CollectionImpl.forEach


generateGlobalKey()

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

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

Parameters

key

any

item

any

Returns (返回)

string

继承自

CollectionImpl.generateGlobalKey


get()

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

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

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

Parameters

key

TKey

Returns (返回)

undefined | T

继承自

CollectionImpl.get


getKeyFromItem()

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

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

Parameters

item

T

Returns (返回)

TKey

继承自

CollectionImpl.getKeyFromItem


has()

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

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

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

Parameters

key

TKey

Returns (返回)

boolean

继承自

CollectionImpl.has


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

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

Parameters

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)
}

继承自

CollectionImpl.insert


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')
}

继承自

CollectionImpl.isReady


keys()

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

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

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

Returns (返回)

IterableIterator<TKey>

继承自

CollectionImpl.keys


map()

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

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

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

类型参数

U

Parameters

callbackfn

(value, key, index) => U

Returns (返回)

U[]

继承自

CollectionImpl.map


onFirstReady()

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

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

注册一个回调函数,以便在集合首次准备就绪时执行。这对于预加载集合很有用。

Parameters

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
})

继承自

CollectionImpl.onFirstReady


onTransactionStateChange()

ts
onTransactionStateChange(): void
onTransactionStateChange(): void

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

当事务状态更改时触发重新计算。此方法应由 Transaction 类在状态更改时调用。

Returns (返回)

void

继承自

CollectionImpl.onTransactionStateChange


preload()

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

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

通过启动同步(如果尚未启动)来预加载集合数据。多次并发调用将共享同一 Promise。

Returns (返回)

Promise<void>

继承自

CollectionImpl.preload


startSyncImmediate()

ts
startSyncImmediate(): void
startSyncImmediate(): void

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

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

Returns (返回)

void

继承自

CollectionImpl.startSyncImmediate


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

继承自

CollectionImpl.stateWhenReady


subscribeChanges()

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

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

订阅集合中的更改

Parameters

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')
})

继承自

CollectionImpl.subscribeChanges


subscribeChangesKey()

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

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

订阅特定键的更改

Parameters

key

TKey

listener

ChangeListener<T, TKey>

__namedParameters
includeInitialState?

boolean = false

Returns (返回)

Function

Returns (返回)

void

继承自

CollectionImpl.subscribeChangesKey


toArrayWhenReady()

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

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

以 Array 的形式获取集合的当前状态,但仅在数据可用时解析。在第一个同步提交完成后等待,然后再解析。

Returns (返回)

Promise<T[]>

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

继承自

CollectionImpl.toArrayWhenReady


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)
}
继承自

CollectionImpl.update

调用签名

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

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

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

类型参数

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)
}
继承自

CollectionImpl.update

调用签名

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

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

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

类型参数

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)
}
继承自

CollectionImpl.update

调用签名

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

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

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

类型参数

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)
}
继承自

CollectionImpl.update


values()

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

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

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

Returns (返回)

IterableIterator<T>

继承自

CollectionImpl.values

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

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

Bytes

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

订阅 Bytes

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

Bytes

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