定义于: 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: 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
CollectionImpl.optimisticDeletes
optimisticUpserts: Map<TKey, T>;
optimisticUpserts: Map<TKey, T>;
定义于: packages/db/src/collection.ts:220
CollectionImpl.optimisticUpserts
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
定义于: packages/db/src/collection.ts:215
CollectionImpl.pendingSyncedTransactions
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
readonly utils: TUtils;
readonly utils: TUtils;
定义于: packages/db/src/collection.ts:84
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
CollectionImpl.commitPendingTransactions
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')
})
CollectionImpl.currentStateAsChanges
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
CollectionImpl.generateGlobalKey
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
CollectionImpl.onTransactionStateChange
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
CollectionImpl.startSyncImmediate
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:2052
订阅集合中的更改
(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')
})
CollectionImpl.subscribeChanges
subscribeChangesKey(
key,
listener,
__namedParameters): () => void
subscribeChangesKey(
key,
listener,
__namedParameters): () => void
定义于: packages/db/src/collection.ts:2197
订阅特定键的更改
TKey
ChangeListener<T, TKey>
boolean = false
Function
void
CollectionImpl.subscribeChangesKey
toArrayWhenReady(): Promise<T[]>
toArrayWhenReady(): Promise<T[]>
定义于: packages/db/src/collection.ts:2197
以 Array 的形式获取集合的当前状态,但仅在数据可用时解析。在第一个同步提交完成后等待,然后再解析。
Promise<T[]>
解析为包含集合中所有项目的 Array 的 Promise
CollectionImpl.toArrayWhenReady
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: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>(id, callback): Transaction
update<TItem>(id, callback): Transaction
定义于: packages/db/src/collection.ts:1731
使用回调函数更新集合中的一个或多个项目
• 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: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)
}
values(): IterableIterator<T>
values(): IterableIterator<T>
定义于: packages/db/src/collection.ts:1744
获取所有值(虚拟派生状态)
IterableIterator<T>
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。