Document reference
Document reference は、個別 document の読み取り、書き込み、削除に使用する、collection 内の特定 record への pointer です。
Document Reference を使用する理由
database 内の特定 document を読み取り、書き込み、または削除する必要があります。document reference は単一 record への直接的な pointer を提供し、collection 全体を query することなく、その record に対する operation を実行できます。
// 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);
概要
document は、relational database の table 内の row、または NoSQL database の document を表します。document reference は、その特定 record への typed pointer として機能します。
document reference は存在しない document を指すこともできます。これにより、reference に対して insert を呼び出して新しい document を作成できます。
collection内の document への reference を取得するには、document ID を指定して doc method を使用します。
const userRef = squid.collection<User>('users').doc('user_123');
クイックスタート
ステップ 1: Collection reference を作成し、document を取得する
interface User {
id: string;
name: string;
email: string;
}
const usersCollection = squid.collection<User>('users');
const userRef = usersCollection.doc('user_123');
ステップ 2: Document data を読み取る
// 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);
}
ステップ 3: Document に data を書き込む
// 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 と snapshots
document reference は、data を読み取る 2 つの方法を提供します。
snapshot()はPromise<T | undefined>を返します。これは現在の document data、または document が存在しない場合はundefinedで resolve されます。one-time read に使用します。snapshots()はT | undefinedの RxJS Observable を返します。document が change するたびに、最新の data を emit します。real-time update に使用します。
// 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);
});
Query result の data getter
query().snapshot() を介して複数の document を query すると、result は DocumentReference<T>[] として返されます。各 document reference は、typed data に access するための 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
}
または、document reference を使用せずに直接 data を取得するには、dereference() を使用します。詳細は Queries を参照してください。
存在しない Document の参照
まだ存在しない document への reference を作成できます。これは新しい document を 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 を自動生成するには、argument なしで doc() を呼び出します。詳細は Document IDs を参照してください。
Error Handling
| Error | 原因 | 解決策 |
|---|---|---|
| Document not found | document が存在しないため、snapshot() が null を返した | data に access する前に null を確認する |
| Invalid document ID | ID format が collection の key schema と一致しない | built-in database では string ID を使用し、external connectorでは object ID を使用する |
| Security rule rejection | mutation が security rules により block された | user が operation の permission を持つことを確認する |
ベストプラクティス
-
document が存在しない可能性があるため、document を読み取る際は常に undefined を確認します。
Client codeconst user = await userRef.snapshot();
if (!user) {
console.log('User not found');
return;
}
console.log(user.name); -
real-time update が必要な UI binding には
snapshots()を使用し、form の事前入力のような one-time read にはsnapshot()を使用します。 -
既存 document を変更する場合は、変更された field のみを送信するため、
insert()よりもupdate()を優先します。詳細は Adding data を参照してください。
関連項目
- Document IDs - built-in database と external database の ID format
- Collection references - collection と table に access する
- Queries - filter、sorting、join を使用して document を query する
- Adding data - insert および update operation
- Deleting data - delete operation