Document reference
Document reference は、コレクション内の特定のレコードを指し示すポインタで、個々のドキュメントの読み取り・書き込み・削除に使用します。
Document reference を使う理由
データベース内の特定のドキュメントを読み取り・書き込み・削除する必要がある場合があります。Document reference は単一レコードへの直接ポインタを提供し、コレクション全体をクエリせずにそのドキュメントに対して操作できます。
// Get a reference to a specific user and read their data
const userRef = squid.collection<User>('users').doc('user_123');
const user = await userRef.snapshot();
console.log(user?.name);
概要
ドキュメントは、リレーショナルデータベースではテーブルの行、NoSQL データベースではドキュメントを指すことがあります。Document reference は、その特定レコードに対する型付きポインタとして機能します。
Document references は存在しないドキュメントを指すこともでき、これは参照に対して insert を呼び出して新しいドキュメントを作成する方法でもあります。
collection 内のドキュメントへの参照を取得するには、doc メソッドに document ID を渡します:
const userRef = squid.collection<User>('users').doc('user_123');
クイックスタート
Step 1: collection reference を作成してドキュメントを取得する
interface User {
id: string;
name: string;
email: string;
}
const usersCollection = squid.collection<User>('users');
const userRef = usersCollection.doc('user_123');
Step 2: ドキュメントデータを読み取る
// Single snapshot (returns the data or undefined if the document doesn't exist)
const user = await userRef.snapshot();
if (user) {
console.log(user.name, user.email);
}
Step 3: ドキュメントにデータを書き込む
// Insert a new document
await usersCollection.doc('new_user').insert({
id: 'new_user',
name: 'Alice',
email: 'alice@example.com',
});
// Update an existing document
await userRef.update({ email: 'newemail@example.com' });
コアコンセプト
snapshot vs snapshots
Document reference はデータを読み取るために 2 つの方法を提供します:
snapshot()はPromise<T | undefined>を返し、現在のドキュメントデータ(またはドキュメントが存在しない場合はundefined)で解決されます。1 回きりの読み取りに使用します。snapshots()はT | undefinedの RxJS Observable を返し、ドキュメントが変更されるたびに最新データを emit します。リアルタイム更新に使用します。
// One-time read (returns the data directly)
const user = await userRef.snapshot();
if (user) {
console.log(user.name); // Typed access to User fields
}
// Real-time subscription
userRef.snapshots().subscribe((user) => {
console.log('User updated:', user);
});
クエリ結果の data getter
query().snapshot() で複数ドキュメントをクエリすると、結果は DocumentReference<T>[] として返されます。各 Document reference には、型付きデータへアクセスするための data getter があります:
const users = await squid.collection<User>('users').query().snapshot();
for (const userRef of users) {
const name: string = userRef.data.name; // Type-safe access via .data
}
または dereference() を使うと、Document reference を介さずに直接データを取得できます。詳細は Queries を参照してください。
存在しないドキュメントの参照
まだ存在しないドキュメントへの参照を作成できます。これは新しいドキュメントを insert する標準的な方法です:
// This document doesn't exist yet
const newUserRef = squid.collection<User>('users').doc('new_user_id');
// Create it by inserting data
await newUserRef.insert({ id: 'new_user_id', name: 'Bob', email: 'bob@example.com' });
自動生成 ID の場合は、引数なしで doc() を呼び出します。詳細は Document IDs を参照してください。
エラーハンドリング
| Error | Cause | Solution |
|---|---|---|
| Document not found | ドキュメントが存在しないため snapshot() が null を返した | data にアクセスする前に null をチェックする |
| Invalid document ID | ID の形式がコレクションのキー schema と一致しない | built-in database には string ID を使用し、external connectors には object ID を使用する |
| Security rule rejection | mutation が security rules によりブロックされた | ユーザーがその操作の権限を持っていることを確認する |
ベストプラクティス
-
ドキュメントは存在しない場合があるため、読み取り時は 必ず undefined をチェック してください:
Client codeconst user = await userRef.snapshot();
if (!user) {
console.log('User not found');
return;
}
console.log(user.name); -
リアルタイム更新が必要な UI バインディング には
snapshots()を使い、フォームの事前入力などの 1 回きりの読み取りにはsnapshot()を使ってください。 -
既存ドキュメントを変更する場合は、変更フィールドのみを送るため
insert()よりupdate()を優先 してください。詳細は Adding data を参照してください。
関連項目
- Document IDs - built-in と external databases の ID 形式
- Collection references - コレクションとテーブルにアクセス
- Queries - フィルタ・ソート・join でドキュメントをクエリ
- Adding data - insert と update 操作
- Deleting data - delete 操作