定义于: 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<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 实例
CollectionConfig<T, TKey, TSchema, TInsertInput>
集合的配置对象
CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>
如果同步配置丢失,则抛出错误
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
定义于: packages/db/src/collection.ts:211
id: string;
id: string;
定义于: packages/db/src/collection.ts:331
optimisticDeletes: Set<TKey>;
optimisticDeletes: Set<TKey>;
定义于: packages/db/src/collection.ts:221
optimisticUpserts: Map<TKey, T>;
optimisticUpserts: Map<TKey, T>;
定义于: packages/db/src/collection.ts:220
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
定义于: packages/db/src/collection.ts:215
syncedData: Map<TKey, T> | SortedMap<TKey, T>;
syncedData: Map<TKey, T> | SortedMap<TKey, T>;
定义于: packages/db/src/collection.ts:216
syncedMetadata: Map<TKey, unknown>;
syncedMetadata: Map<TKey, unknown>;
定义于: packages/db/src/collection.ts:217
transactions: SortedMap<string, Transaction<any>>;
transactions: SortedMap<string, Transaction<any>>;
定义于: packages/db/src/collection.ts:214
utils: Record<string, Fn> = {};
utils: Record<string, Fn> = {};
定义于: packages/db/src/collection.ts:238
get indexes(): Map<number, BaseIndex<TKey>>
get indexes(): Map<number, BaseIndex<TKey>>
定义于: packages/db/src/collection.ts:1439
获取用于查询优化的已解析索引
Map<number, BaseIndex<TKey>>
get size(): number
get size(): number
定义于: packages/db/src/collection.ts:995
获取集合的当前大小 (缓存)
number
get state(): Map<TKey, T>
get state(): Map<TKey, T>
定义于: packages/db/src/collection.ts:2038
将集合的当前状态作为 Map 获取
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"))
}
Map<TKey, T>
包含集合中所有项目的 Map,键是标识符
get status(): CollectionStatus
get status(): CollectionStatus
定义于: packages/db/src/collection.ts:336
获取集合的当前状态
get toArray(): T[]
get toArray(): T[]
定义于: packages/db/src/collection.ts:2071
将集合的当前状态作为 Array 获取
T[]
包含集合中所有项目的 Array
iterator: IterableIterator<[TKey, T]>
iterator: IterableIterator<[TKey, T]>
定义于: packages/db/src/collection.ts:1046
获取所有条目 (虚拟派生状态)
IterableIterator<[TKey, T]>
cleanup(): Promise<void>
cleanup(): Promise<void>
定义于: packages/db/src/collection.ts:583
通过停止同步和清除数据来清理集合。可以手动调用,也可以由垃圾回收自动调用。
Promise<void>
commitPendingTransactions(): void
commitPendingTransactions(): void
定义于: packages/db/src/collection.ts:1082
如果当前没有活动事务,则尝试提交挂起的同步事务。此方法处理来自挂起事务的操作,并将它们应用于同步数据。
void
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
定义于: packages/db/src/collection.ts:1344
在集合上创建索引以加快查询速度。索引通过允许二分搜索和范围查询而不是完整扫描来显著提高查询性能。
• TResolver extends IndexResolver<TKey> = typeof BTreeIndex
索引解析器的类型(构造函数或异步加载器)
(row) => any
从每个项目提取索引值的函数
IndexOptions<TResolver> = {}
配置,包括索引类型和特定于类型的选项
IndexProxy<TKey>
提供索引可用时访问索引的代理
// 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(options): ChangeMessage<T, string | number>[]
currentStateAsChanges(options): ChangeMessage<T, string | number>[]
定义于: packages/db/src/collection.ts:2113
将集合的当前状态作为更改数组返回
CurrentStateAsChangesOptions<T> = {}
选项,包括可选的 where 过滤器
ChangeMessage<T, string | number>[]
更改数组
// 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(keys, config?): Transaction<any>
delete(keys, config?): Transaction<any>
定义于: packages/db/src/collection.ts:1939
从集合中删除一个或多个项目
要删除的单个键或键数组
TKey | TKey[]
可选配置,包括元数据
Transaction<any>
代表删除操作的 Transaction 对象
// 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
// 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
// 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
// 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(): IterableIterator<[TKey, T]>
entries(): IterableIterator<[TKey, T]>
定义于: packages/db/src/collection.ts:1034
获取所有条目 (虚拟派生状态)
IterableIterator<[TKey, T]>
forEach(callbackfn): void
forEach(callbackfn): void
定义于: packages/db/src/collection.ts:1055
为集合中的每个条目执行一个回调函数
(value, key, index) => void
void
generateGlobalKey(key, item): string
generateGlobalKey(key, item): string
定义于: packages/db/src/collection.ts:1306
any
any
string
get(key): undefined | T
get(key): undefined | T
定义于: packages/db/src/collection.ts:959
获取键的当前值 (虚拟派生状态)
TKey
undefined | T
getKeyFromItem(item): TKey
getKeyFromItem(item): TKey
定义于: packages/db/src/collection.ts:1302
T
TKey
has(key): boolean
has(key): boolean
定义于: packages/db/src/collection.ts:977
检查集合中是否存在某个键 (虚拟派生状态)
TKey
boolean
insert(data, config?):
| Transaction<Record<string, unknown>>
| Transaction<T>
insert(data, config?):
| Transaction<Record<string, unknown>>
| Transaction<T>
定义于: packages/db/src/collection.ts:1594
将一个或多个项目插入到集合中
TInsertInput | TInsertInput[]
可选配置,包括元数据
| Transaction<Record<string, unknown>> | Transaction<T>
代表插入操作的 Transaction 对象
如果数据通过模式验证失败
// 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
// 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
// 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
// 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(): boolean
isReady(): boolean
定义于: packages/db/src/collection.ts:294
检查集合是否已准备好使用。如果集合已被其同步实现标记为就绪,则返回 true。
boolean
如果集合已准备好,则为 true,否则为 false
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(): IterableIterator<TKey>
keys(): IterableIterator<TKey>
定义于: packages/db/src/collection.ts:1002
获取所有键 (虚拟派生状态)
IterableIterator<TKey>
map<U>(callbackfn): U[]
map<U>(callbackfn): U[]
定义于: packages/db/src/collection.ts:1067
通过对集合中的每个条目调用函数来创建结果的新数组
• U
(value, key, index) => U
U[]
onFirstReady(callback): void
onFirstReady(callback): void
定义于: packages/db/src/collection.ts:272
注册一个回调函数,当集合首次准备好时执行。用于预加载集合。
() => void
集合首次准备好时调用的函数
void
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(): void
onTransactionStateChange(): void
定义于: packages/db/src/collection.ts:2271
当事务发生变化时触发重新计算。 Transaction 类应调用此方法来更新状态。
void
preload(): Promise<void>
preload(): Promise<void>
定义于: packages/db/src/collection.ts:544
预加载集合数据,如果尚未启动则启动同步。多个并发调用将共享同一个 Promise。
Promise<void>
startSyncImmediate(): void
startSyncImmediate(): void
定义于: packages/db/src/collection.ts:450
立即启动同步 - 编译查询的内部方法。此方法绕过懒加载,用于实时查询结果等特殊情况。
void
stateWhenReady(): Promise<Map<TKey, T>>
stateWhenReady(): Promise<Map<TKey, T>>
定义于: packages/db/src/collection.ts:2052
将集合的当前状态作为 Map 获取,但仅在数据可用时解析。在解析之前等待第一次同步提交完成。
Promise<Map<TKey, T>>
解析为包含集合中所有项目的 Map 的 Promise
subscribeChanges(callback, options): () => void
subscribeChanges(callback, options): () => void
定义于: packages/db/src/collection.ts:2158
订阅集合中的更改
(changes) => void
项目更改时调用的函数
SubscribeChangesOptions<T> = {}
订阅选项,包括 includeInitialState 和 where 过滤器
Function
退订函数 - 调用此函数可停止监听更改
void
// 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()
// 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 })
// 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'
})
// 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(
key,
listener,
__namedParameters): () => void
subscribeChangesKey(
key,
listener,
__namedParameters): () => void
定义于: packages/db/src/collection.ts:2197
订阅特定键的更改
TKey
ChangeListener<T, TKey>
boolean = false
Function
void
toArrayWhenReady(): Promise<T[]>
toArrayWhenReady(): Promise<T[]>
定义于: packages/db/src/collection.ts:2081
将集合的当前状态作为 Array 获取,但仅在数据可用时解析。在解析之前等待第一次同步提交完成。
Promise<T[]>
解析为包含集合中所有项目的 Array 的 Promise
update<TItem>(key, callback): Transaction
update<TItem>(key, callback): Transaction
定义于: packages/db/src/collection.ts:1725
使用回调函数更新集合中的一个或多个项目
• TItem extends object = T
unknown[]
(drafts) => void
代表更新操作的 Transaction 对象
如果更新的数据通过模式验证失败
// 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
// 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
// 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
// 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)
}
update<TItem>(
keys,
config,
callback): Transaction
update<TItem>(
keys,
config,
callback): Transaction
定义于: packages/db/src/collection.ts:1731
使用回调函数更新集合中的一个或多个项目
• TItem extends object = T
unknown[]
要更新的单个键或键数组
(drafts) => void
代表更新操作的 Transaction 对象
如果更新的数据通过模式验证失败
// 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
// 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
// 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
// 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)
}
update<TItem>(id, callback): Transaction
update<TItem>(id, callback): Transaction
定义于: packages/db/src/collection.ts:1738
使用回调函数更新集合中的一个或多个项目
• TItem extends object = T
unknown
(draft) => void
代表更新操作的 Transaction 对象
如果更新的数据通过模式验证失败
// 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
// 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
// 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
// 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)
}
update<TItem>(
id,
config,
callback): Transaction
update<TItem>(
id,
config,
callback): Transaction
定义于: packages/db/src/collection.ts:1744
使用回调函数更新集合中的一个或多个项目
• TItem extends object = T
unknown
(draft) => void
代表更新操作的 Transaction 对象
如果更新的数据通过模式验证失败
// 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
// 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
// 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
// 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(): IterableIterator<T>
values(): IterableIterator<T>
定义于: packages/db/src/collection.ts:1022
获取所有值 (虚拟派生状态)
IterableIterator<T>
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。