ミューテーション
ミューテーションとは、ドキュメントのデータを変更するアクションのことです。楽観的更新を利用して、迅速でレスポンシブなユーザーエクスペリエンスを提供します。
トランザクション(transaction)で実行されない限り、すべてのミューテーションは、サーバー上でミューテーションが適用された後に解決されるPromise
を返します。
ミューテーションの適用
ミューテーションは楽観的にローカルで適用され、クライアント側に即座に反映されます。その後、変更は一貫性がありクリーンなデータ状態を保証するために、非同期的にサーバーへ送信されます。
ミューテーションには、insert
、delete
、およびupdate
の3種類があります。これらはすべて、document reference上で実行されます。
挿入
挿入は、新しいドキュメントを作成するために使用されます。コレクションに新しいドキュメントを挿入するには、DocumentReference
上のinsert
メソッドを呼び出し、新しいドキュメントデータを引数として渡します:
try {
await squid.collection<User>('users').doc('new_user_id').insert({
name: 'John Doe',
email: 'johndoe@example.com',
});
console.log('User added successfully');
} catch (error) {
console.error(`Failed to add user ${error}`);
}
バックエンドのセキュリティルールを使用すると、各ミューテーションを誰が実行できるかを細かく制御できます。これらのルールは、変更前後のドキュメントのスナップショットを含む、ミューテーションに関するすべての詳細情報を持つMutationContext
をパラメーターとして受け取ります。ルールの書き方については、security rulesを参照してください。
一括挿入
insertMany
メソッドは、複数のドキュメントを一度に効率的に挿入および/または更新するために使用されます。以下の例は、新しいユーザードキュメントの配列を追加するものです:
const newDocuments = [
{
id: 'new_user_id1',
data: {
name: 'John Doe',
email: 'johndoe@example.com',
},
},
{
id: 'new_user_id2',
data: {
name: 'Jan Smith',
email: 'jansmith@example.com',
},
},
];
try {
await squid.collection<User>('users').insertMany(newDocuments);
console.log('Users added successfully');
} catch (error) {
console.error(`Failed to add users ${error}`);
}
更新
ドキュメントを更新するには、DocumentReference
上のupdate
メソッドを呼び出し、部分更新データを含むオブジェクトを引数として渡します:
try {
await squid.collection<User>('users').doc('existing_user_id').update({ email: 'new_email@example.com' });
console.log('User updated successfully');
} catch (error) {
console.error(`Failed to update user ${error}`);
}
また、DocumentReference
上でsetInPath
メソッドを呼び出し、プロパティへのpath
と新しい値を引数として渡すことで、ドキュメントの特定のプロパティを更新することもできます:
const userRef = squid.collection<User>('users').doc('existing_user_id');
try {
await userRef.setInPath('address.street', 'Main');
console.log('Updated successfully');
} catch (error) {
console.error(`Failed to update user ${error}`);
}
ドキュメントの特定のプロパティを削除するには、DocumentReference
上でdeleteInPath
メソッドを呼び出し、削除したいプロパティへのpath
を引数として渡します:
const userRef = squid.collection<User>('users').doc('existing_user_id');
try {
await userRef.deleteInPath('email');
console.log('User email deleted successfully');
} catch (error) {
console.error(`Failed to delete user email ${error}`);
}
削除
ドキュメントを削除するには、DocumentReference
上のdelete
メソッドを呼び出します:
const userRef = squid.collection<User>('users').doc('existing_user_id');
try {
await userRef.delete();
console.log('User deleted successfully');
} catch (error) {
console.error(`Failed to delete user ${error}`);
}
一括削除
複数のドキュメントを一括で削除するには、deleteMany
メソッドを使用します。deleteMany
は、ドキュメントまたはドキュメントIDの配列をパラメーターとして受け取ります:
const staleDocs = await squid.collection<User>('users').query().eq('pending-delete', true);
try {
await squid.collection<User>('users').deleteMany(staleDocs);
console.log('users successfully deleted');
} catch (error) {
console.error(`Failed to delete users ${error}`);
}