メインコンテンツまでスキップ

Document reference

Document reference は、コレクション内の特定のレコードを指し示すポインタで、個々のドキュメントの読み取り・書き込み・削除に使用します。

Document reference を使う理由

データベース内の特定のドキュメントを読み取り・書き込み・削除する必要がある場合があります。Document reference は単一レコードへの直接ポインタを提供し、コレクション全体をクエリせずにそのドキュメントに対して操作できます。

Client code
// 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 を渡します:

Client code
const userRef = squid.collection<User>('users').doc('user_123');

クイックスタート

Step 1: collection reference を作成してドキュメントを取得する

Client code
interface User {
id: string;
name: string;
email: string;
}

const usersCollection = squid.collection<User>('users');
const userRef = usersCollection.doc('user_123');

Step 2: ドキュメントデータを読み取る

Client code
// 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: ドキュメントにデータを書き込む

Client code
// 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 | undefinedRxJS Observable を返し、ドキュメントが変更されるたびに最新データを emit します。リアルタイム更新に使用します。
Client code
// 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 があります:

Client code
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 する標準的な方法です:

Client code
// 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 を参照してください。

エラーハンドリング

ErrorCauseSolution
Document not foundドキュメントが存在しないため snapshot()null を返したdata にアクセスする前に null をチェックする
Invalid document IDID の形式がコレクションのキー schema と一致しないbuilt-in database には string ID を使用し、external connectors には object ID を使用する
Security rule rejectionmutation が security rules によりブロックされたユーザーがその操作の権限を持っていることを確認する

ベストプラクティス

  1. ドキュメントは存在しない場合があるため、読み取り時は 必ず undefined をチェック してください:

    Client code
    const user = await userRef.snapshot();
    if (!user) {
    console.log('User not found');
    return;
    }
    console.log(user.name);
  2. リアルタイム更新が必要な UI バインディング には snapshots() を使い、フォームの事前入力などの 1 回きりの読み取りには snapshot() を使ってください。

  3. 既存ドキュメントを変更する場合は、変更フィールドのみを送るため insert() より update() を優先 してください。詳細は Adding data を参照してください。

関連項目