본문으로 건너뛰기

인터페이스: Collection<T, TKey, TUtils, TSchema, TInsertInput>

정의 위치: packages/db/src/collection/index.ts:57

데이터 형식 T와 유틸리티 TUtils를 모두 포함하는 향상된 Collection 인터페이스입니다.

상속

타입 매개변수

T

T extends object = Record<string, unknown>

컬렉션 항목의 타입입니다.

TKey

TKey extends string | number = string | number

컬렉션 키의 타입입니다

TUtils

TUtils extends UtilsRecord = UtilsRecord

유틸리티 레코드 타입입니다

TSchema

TSchema extends StandardSchemaV1 = StandardSchemaV1

TInsertInput

TInsertInput extends object = T

삽입 작업을 위한 형식입니다(기본값이 있는 스키마에서는 T와 다를 수 있음).

속성

_lifecycle

_lifecycle: CollectionLifecycleManager<T, TKey, TSchema, TInsertInput>;

정의 위치: packages/db/src/collection/index.ts:292

상속받은 속성

CollectionImpl._lifecycle


_state

_state: CollectionStateManager<T, TKey, TSchema, TInsertInput>;

정의 위치: packages/db/src/collection/index.ts:304

상속받은 속성

CollectionImpl._state


_sync

_sync: CollectionSyncManager<T, TKey, TSchema, TInsertInput>;

정의 위치: packages/db/src/collection/index.ts:293

상속받은 속성

CollectionImpl._sync


config

config: CollectionConfig<T, TKey, TSchema>;

정의 위치: packages/db/src/collection/index.ts:283

상속받은 속성

CollectionImpl.config


deferDataRefresh

deferDataRefresh: Promise<void> | null = null;

정의 위치: packages/db/src/collection/index.ts:311

설정되면 컬렉션 소비자는 이 promise가 확인될 때까지 수신 데이터 새로 고침 처리를 지연해야 합니다. 이렇게 하면 보류 중인 쓰기가 적용되는 동안 오래된 데이터가 낙관적 상태를 덮어쓰는 것을 방지합니다.

상속받은 속성

CollectionImpl.deferDataRefresh


id

id: string;

정의 위치: packages/db/src/collection/index.ts:282

상속받은 속성

CollectionImpl.id


singleResult?

readonly optional singleResult: true;

정의 위치: packages/db/src/collection/index.ts:65


utils

readonly utils: TUtils;

정의 위치: packages/db/src/collection/index.ts:64

재정의된 메서드

CollectionImpl.utils

접근자

_layoutRevision

가져오기 시그니처

get _layoutRevision(): number;

정의 위치: packages/db/src/collection/index.ts:438

명시적 레이아웃 전용 게시의 단조 증가 revision입니다. 내부용 — 빈 ready 이벤트와 구분하는 데 사용됩니다.

반환값

number

상속받은 속성

CollectionImpl._layoutRevision


_stateRevision

가져오기 시그니처

get _stateRevision(): number;

정의 위치: packages/db/src/collection/index.ts:430

컬렉션의 표시 상태에 대한 단조 증가 revision입니다. 구독자가 없는 경우에도 변경 사항의 커밋된 각 배치마다 한 번씩 증가합니다. 내부용 — 라이브 쿼리 옵저버의 스냅샷 캐시에서 사용됩니다.

반환값

number

상속받은 속성

CollectionImpl._stateRevision


compareOptions

가져오기 시그니처

get compareOptions(): StringCollationConfig;

정의 위치: packages/db/src/collection/index.ts:698

반환값

StringCollationConfig

상속받은 속성

CollectionImpl.compareOptions


인덱스

가져오기 시그니처

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

정의 위치: packages/db/src/collection/index.ts:683

쿼리 최적화를 위해 확인된 인덱스를 가져옵니다

반환값

Map&lt;number, BaseIndex&lt;TKey>>

상속받은 속성

CollectionImpl.indexes


isLoadingSubset

가져오기 시그니처

get isLoadingSubset(): boolean;

정의 위치: packages/db/src/collection/index.ts:491

컬렉션이 현재 더 많은 데이터를 로드 중인지 확인합니다

반환값

boolean

컬렉션에 보류 중인 추가 로드 작업이 있으면 true이고, 그렇지 않으면 false입니다

상속받은 속성

CollectionImpl.isLoadingSubset


크기

가져오기 시그니처

get size(): number;

정의 위치: packages/db/src/collection/index.ts:548

컬렉션의 현재 크기를 가져옵니다(캐시됨)

반환값

number

상속받은 속성

CollectionImpl.size


state

가져오기 시그니처

get state(): Map<TKey, WithVirtualProps<TOutput, TKey>>;

정의 위치: packages/db/src/collection/index.ts:875

컬렉션의 현재 상태를 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"))
}
반환값

Map&lt;TKey, WithVirtualProps&lt;TOutput, TKey>>

식별자를 키로 하여 컬렉션의 모든 항목을 포함하는 Map입니다

상속받은 속성

CollectionImpl.state


status

가져오기 시그니처

get status(): CollectionStatus;

정의 위치: packages/db/src/collection/index.ts:414

컬렉션의 현재 상태를 가져옵니다

반환값

CollectionStatus

상속받은 속성

CollectionImpl.status


subscriberCount

가져오기 시그니처

get subscriberCount(): number;

정의 위치: packages/db/src/collection/index.ts:421

컬렉션의 구독자 수를 가져옵니다

반환값

number

상속받은 속성

CollectionImpl.subscriberCount


toArray

가져오기 시그니처

get toArray(): WithVirtualProps<TOutput, TKey>[];

정의 위치: packages/db/src/collection/index.ts:904

컬렉션의 현재 상태를 Array로 가져옵니다

반환값

WithVirtualProps&lt;TOutput, TKey>[]

컬렉션의 모든 항목을 포함하는 Array입니다

상속받은 속성

CollectionImpl.toArray

메서드

_deferPublication()

_deferPublication(): PublicationDeferral;

정의 위치: packages/db/src/collection/index.ts:453

일관된 다중 컬렉션 커밋이 끝날 때까지 구독자 이벤트를 지연합니다.

반환값

PublicationDeferral

상속받은 속성

CollectionImpl._deferPublication


_deferSyncStart()

_deferSyncStart(): boolean;

정의 위치: packages/db/src/collection/index.ts:514

Internal

반환값

boolean

상속받은 속성

CollectionImpl._deferSyncStart


_hasHydratedKey()

_hasHydratedKey(key): boolean;

정의 위치: packages/db/src/collection/index.ts:509

Internal

매개변수

key

TKey

반환값

boolean

상속받은 속성

CollectionImpl._hasHydratedKey


_markLayoutChange()

_markLayoutChange(): void;

정의 위치: packages/db/src/collection/index.ts:448

활성 sync 트랜잭션을 레이아웃 변경으로 표시합니다. 내부용입니다.

반환값

void

상속받은 속성

CollectionImpl._markLayoutChange


_resumeSyncStart()

_resumeSyncStart(): void;

정의 위치: packages/db/src/collection/index.ts:519

Internal

반환값

void

상속받은 속성

CollectionImpl._resumeSyncStart


_setTransactionScope()

_setTransactionScope(transactionScope): void;

정의 위치: packages/db/src/collection/index.ts:504

Internal

매개변수

transactionScope

TransactionScope

반환값

void

상속받은 속성

CollectionImpl._setTransactionScope


_subscribeLayoutChanges()

_subscribeLayoutChanges(listener): () => void;

정의 위치: packages/db/src/collection/index.ts:443

레이아웃 전용 게시를 구독합니다. 내부 옵저버 채널입니다.

매개변수

리스너

() => void

반환값

(): void;
반환값

void

상속받은 속성

CollectionImpl._subscribeLayoutChanges


[iterator]()

iterator: IterableIterator<[TKey, WithVirtualProps<T, TKey>]>;

정의 위치: packages/db/src/collection/index.ts:586

모든 항목을 가져옵니다(가상 파생 상태)

반환값

IterableIterator&lt;[TKey, WithVirtualProps&lt;T, TKey>]>

상속받은 속성

CollectionImpl.[iterator]


cleanup()

cleanup(): Promise<void>;

정의 위치: packages/db/src/collection/index.ts:1043

동기화를 중지하고 데이터를 삭제하여 컬렉션을 정리합니다. 수동으로 호출하거나 가비지 컬렉션에 의해 자동으로 호출할 수 있습니다.

반환값

Promise&lt;void>

상속받은 속성

CollectionImpl.cleanup


createIndex()

createIndex<TIndexType>(indexCallback, config): BaseIndex<TKey>;

정의 위치: packages/db/src/collection/index.ts:652

더 빠른 쿼리를 위해 컬렉션에 인덱스를 생성합니다. 인덱스를 사용하면 전체 스캔 대신 상수 시간 조회와 로그 시간 범위 쿼리가 가능해져 쿼리 성능이 크게 향상됩니다.

타입 매개변수

TIndexType

TIndexType extends IndexConstructor&lt;TKey>

매개변수

indexCallback

(row) => any

각 항목에서 인덱싱된 값을 추출하는 함수입니다

config

IndexOptions&lt;TIndexType> = {}

인덱스 유형 및 유형별 옵션을 포함하는 구성입니다

반환값

BaseIndex&lt;TKey>

생성된 인덱스입니다

예제

import { BasicIndex } from '@tanstack/db'

// Create an index with explicit type
const ageIndex = collection.createIndex((row) => row.age, {
indexType: BasicIndex
})

// Create an index with collection's default type
const nameIndex = collection.createIndex((row) => row.name)

상속받은 속성

CollectionImpl.createIndex


currentStateAsChanges()

currentStateAsChanges(options): 
| void
| ChangeMessage<WithVirtualProps<T, TKey>, string | number>[];

정의 위치: packages/db/src/collection/index.ts:942

컬렉션의 현재 상태를 변경 사항 배열로 반환합니다

매개변수

options

CurrentStateAsChangesOptions = {}

선택적 where 필터를 포함하는 옵션입니다

반환값

| void | ChangeMessage&lt;WithVirtualProps&lt;T, TKey>, 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')
})

상속받은 속성

CollectionImpl.currentStateAsChanges


delete()

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

정의 위치: packages/db/src/collection/index.ts:852

컬렉션에서 하나 이상의 항목을 삭제합니다

매개변수

keys

삭제할 단일 키 또는 키 배열입니다

TKey | TKey[]

config?

OperationConfig

메타데이터를 포함할 수 있는 선택적 구성입니다

반환값

Transaction&lt;any>

삭제 작업을 나타내는 Transaction 객체입니다

예제

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

상속받은 속성

CollectionImpl.delete


entries()

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

정의 위치: packages/db/src/collection/index.ts:574

모든 항목을 가져옵니다(가상 파생 상태)

반환값

IterableIterator&lt;[TKey, WithVirtualProps&lt;T, TKey>]>

상속받은 속성

CollectionImpl.entries


forEach()

forEach(callbackfn): void;

정의 위치: packages/db/src/collection/index.ts:595

컬렉션의 각 항목에 대해 콜백을 실행합니다

매개변수

callbackfn

(value, key, index) => void

반환값

void

상속받은 속성

CollectionImpl.forEach


get()

get(key): 
| WithVirtualProps<T, TKey>
| undefined;

정의 위치: packages/db/src/collection/index.ts:534

키의 현재 값을 가져옵니다(가상 파생 상태)

매개변수

key

TKey

반환값

| WithVirtualProps&lt;T, TKey> | undefined

상속받은 속성

CollectionImpl.get


getIndexMetadata()

getIndexMetadata(): CollectionIndexMetadata[];

정의 위치: packages/db/src/collection/index.ts:676

indexId를 기준으로 정렬된 현재 인덱스 메타데이터의 스냅샷을 반환합니다. 인덱스가 이벤트 리스너 연결 전에 생성된 경우 영속성 래퍼가 이를 사용하여 인덱스 상태를 부트스트랩할 수 있습니다.

반환값

CollectionIndexMetadata[]

상속받은 속성

CollectionImpl.getIndexMetadata


getKeyFromItem()

getKeyFromItem(item): TKey;

정의 위치: packages/db/src/collection/index.ts:626

매개변수

item

T

반환값

TKey

상속받은 속성

CollectionImpl.getKeyFromItem


has()

has(key): boolean;

정의 위치: packages/db/src/collection/index.ts:541

컬렉션에 키가 존재하는지 확인합니다(가상 파생 상태)

매개변수

key

TKey

반환값

boolean

상속받은 속성

CollectionImpl.has


insert()

insert(data, config?): Transaction<Record<string, unknown>>;

정의 위치: packages/db/src/collection/index.ts:739

컬렉션에 하나 이상의 항목을 삽입합니다

매개변수

data

TInsertInput | TInsertInput[]

config?

InsertConfig

메타데이터를 포함할 수 있는 선택적 구성입니다

반환값

Transaction&lt;Record&lt;string, unknown>>

삽입 작업을 나타내는 Transaction 객체입니다

발생하는 오류

데이터가 스키마 검증에 실패한 경우

예제

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

상속받은 속성

CollectionImpl.insert


isReady()

isReady(): boolean;

정의 위치: packages/db/src/collection/index.ts:483

컬렉션을 사용할 준비가 되었는지 확인합니다 동기화 구현에 의해 컬렉션이 준비된 것으로 표시되었으면 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')
}

상속받은 속성

CollectionImpl.isReady


keys()

keys(): IterableIterator<TKey>;

정의 위치: packages/db/src/collection/index.ts:555

모든 키를 가져옵니다(가상 파생 상태)

반환값

IterableIterator&lt;TKey>

상속받은 속성

CollectionImpl.keys


map()

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

정의 위치: packages/db/src/collection/index.ts:611

컬렉션의 각 항목에 대해 함수를 호출한 결과로 새 배열을 생성합니다

타입 매개변수

U

U

매개변수

callbackfn

(value, key, index) => U

반환값

U[]

상속받은 속성

CollectionImpl.map


off()

off<T>(event, callback): void;

정의 위치: packages/db/src/collection/index.ts:1022

컬렉션 이벤트 구독을 취소합니다

타입 매개변수

T

T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"

매개변수

event

T

callback

CollectionEventHandler&lt;T>

반환값

void

상속받은 속성

CollectionImpl.off


on()

on<T>(event, callback): () => void;

정의 위치: packages/db/src/collection/index.ts:1002

컬렉션 이벤트를 구독합니다

타입 매개변수

T

T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"

매개변수

event

T

callback

CollectionEventHandler&lt;T>

반환값

(): void;
반환값

void

상속받은 속성

CollectionImpl.on


once()

once<T>(event, callback): () => void;

정의 위치: packages/db/src/collection/index.ts:1012

컬렉션 이벤트를 한 번 구독합니다

타입 매개변수

T

T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"

매개변수

event

T

callback

CollectionEventHandler&lt;T>

반환값

(): void;
반환값

void

상속받은 속성

CollectionImpl.once


onFirstReady()

onFirstReady(callback): () => void;

정의 위치: packages/db/src/collection/index.ts:467

컬렉션이 처음 준비될 때 실행할 콜백을 등록합니다 컬렉션을 미리 로드할 때 유용합니다

매개변수

callback

() => void

컬렉션이 처음 준비될 때 호출할 함수입니다

반환값

(): void;
반환값

void

예제

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

상속받은 속성

CollectionImpl.onFirstReady


preload()

preload(): Promise<void>;

정의 위치: packages/db/src/collection/index.ts:527

아직 시작되지 않았다면 동기화를 시작하여 컬렉션 데이터를 미리 로드합니다 여러 동시 호출은 동일한 프로미스를 공유합니다

반환값

Promise&lt;void>

상속받은 속성

CollectionImpl.preload


removeIndex()

removeIndex(indexOrId): boolean;

정의 위치: packages/db/src/collection/index.ts:667

createIndex로 생성된 인덱스를 제거합니다. 인덱스가 존재하여 제거되었으면 true를 반환합니다.

최선 노력 의미 체계: 인덱스를 제거하면 컬렉션 쿼리 계획에서 분리되도록 보장됩니다. 기존 인덱스 프록시 참조는 제거 후 유효하지 않은 것으로 처리해야 합니다.

매개변수

indexOrId

number | BaseIndex&lt;TKey>

반환값

boolean

상속받은 속성

CollectionImpl.removeIndex


startSyncImmediate()

startSyncImmediate(): void;

정의 위치: packages/db/src/collection/index.ts:499

동기화를 즉시 시작합니다 - 컴파일된 쿼리를 위한 내부 메서드입니다 라이브 쿼리 결과와 같은 특수한 경우에 지연 로딩을 우회합니다

반환값

void

상속받은 속성

CollectionImpl.startSyncImmediate


stateWhenReady()

stateWhenReady(): Promise<Map<TKey, WithVirtualProps<T, TKey>>>;

정의 위치: packages/db/src/collection/index.ts:889

컬렉션의 현재 상태를 Map으로 가져오지만, 데이터를 사용할 수 있을 때만 확인됩니다 확인되기 전에 첫 번째 동기화 커밋이 완료될 때까지 기다립니다

반환값

Promise&lt;Map&lt;TKey, WithVirtualProps&lt;T, TKey>>>

컬렉션의 모든 항목을 포함하는 Map으로 확인되는 프로미스입니다

상속받은 속성

CollectionImpl.stateWhenReady


subscribeChanges()

subscribeChanges(callback, options): CollectionSubscription;

정의 위치: packages/db/src/collection/index.ts:990

컬렉션의 변경 사항을 구독합니다

매개변수

callback

(changes) => void

항목이 변경될 때 호출되는 함수입니다

options

SubscribeChangesOptions&lt;T, TKey> = {}

includeInitialState 및 where 필터를 포함하는 구독 옵션입니다

반환값

CollectionSubscription

구독 취소 함수입니다 - 변경 사항 수신을 중지하려면 호출합니다

예제

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

// Later: subscription.unsubscribe()
// Include current state immediately
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, { includeInitialState: true })
// Subscribe only to changes matching a condition using where callback
import { eq } from "@tanstack/db"

const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
where: (row) => eq(row.status, "active")
})
// Using multiple conditions with and()
import { and, eq, gt } from "@tanstack/db"

const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
where: (row) => and(eq(row.status, "active"), gt(row.priority, 5))
})

상속받은 속성

CollectionImpl.subscribeChanges


toArrayWhenReady()

toArrayWhenReady(): Promise<WithVirtualProps<T, TKey>[]>;

정의 위치: packages/db/src/collection/index.ts:914

컬렉션의 현재 상태를 Array로 가져오지만, 데이터를 사용할 수 있을 때만 확인됩니다 확인되기 전에 첫 번째 동기화 커밋이 완료될 때까지 기다립니다

반환값

Promise&lt;WithVirtualProps&lt;T, TKey>[]>

컬렉션의 모든 항목을 포함하는 Array로 확인되는 프로미스입니다

상속받은 속성

CollectionImpl.toArrayWhenReady


update()

호출 시그니처

update(key, callback): Transaction;

정의 위치: packages/db/src/collection/index.ts:784

콜백 함수를 사용하여 컬렉션의 하나 이상의 항목을 업데이트합니다

매개변수
key

unknown[]

callback

(drafts) => void

반환값

Transaction

업데이트 작업을 나타내는 Transaction 객체입니다

발생하는 오류

업데이트된 데이터가 스키마 검증에 실패한 경우

예제
// 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 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)
}
상속됨

CollectionImpl.update

호출 시그니처

update(
keys,
config,
callback): Transaction;

정의 위치: packages/db/src/collection/index.ts:790

콜백 함수를 사용하여 컬렉션의 하나 이상의 항목을 업데이트합니다

매개변수
keys

unknown[]

업데이트할 단일 키 또는 키 배열입니다

config

OperationConfig

callback

(drafts) => void

반환값

Transaction

업데이트 작업을 나타내는 Transaction 객체입니다

발생하는 오류

업데이트된 데이터가 스키마 검증에 실패한 경우

예제
// 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 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)
}
상속됨

CollectionImpl.update

호출 시그니처

update(id, callback): Transaction;

정의 위치: packages/db/src/collection/index.ts:797

콜백 함수를 사용하여 컬렉션의 하나 이상의 항목을 업데이트합니다

매개변수
id

unknown

callback

(draft) => void

반환값

Transaction

업데이트 작업을 나타내는 Transaction 객체입니다

발생하는 오류

업데이트된 데이터가 스키마 검증에 실패한 경우

예제
// 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 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)
}
상속됨

CollectionImpl.update

호출 시그니처

update(
id,
config,
callback): Transaction;

정의 위치: packages/db/src/collection/index.ts:803

콜백 함수를 사용하여 컬렉션의 하나 이상의 항목을 업데이트합니다

매개변수
id

unknown

config

OperationConfig

callback

(draft) => void

반환값

Transaction

업데이트 작업을 나타내는 Transaction 객체입니다

발생하는 오류

업데이트된 데이터가 스키마 검증에 실패한 경우

예제
// 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 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)
}
상속됨

CollectionImpl.update


validateData()

validateData(
data,
type,
key?): T;

정의 위치: packages/db/src/collection/index.ts:690

데이터를 스키마에 대해 검증합니다

매개변수

data

unknown

type

"insert" | "update"

key?

TKey

반환값

T

상속받은 속성

CollectionImpl.validateData


values()

values(): IterableIterator<WithVirtualProps<T, TKey>>;

정의 위치: packages/db/src/collection/index.ts:562

모든 값을 가져옵니다(가상 파생 상태)

반환값

IterableIterator&lt;WithVirtualProps&lt;T, TKey>>

상속받은 속성

CollectionImpl.values


waitFor()

waitFor<T>(event, timeout?): Promise<AllCollectionEvents[T]>;

정의 위치: packages/db/src/collection/index.ts:1032

컬렉션 이벤트를 기다립니다

타입 매개변수

T

T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"

매개변수

event

T

timeout?

number

반환값

Promise&lt;AllCollectionEvents[T]>

상속받은 속성

CollectionImpl.waitFor