0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Cloud Functions バックグラウンド関数でFirestoreのサブコレクションが更新されたことを検知し、同階層にログを作成する

Posted at

Firestoreでドキュメントの作成時にや削除時にトリガーして使用することを想定しています。
ログデータ作成はアプリ側ではなくバックグラウンドで安全に処理したいですね。

exports.myFunction = functions.firestore
  .document('collection/{docId}/subcollection/{subId}')
  .onCreate((snap, context) => {
    const data = snap.data();

    // ログ用のデータを作成する
    const logData = {
      subcollectionId: context.params.subId,
      createdAt: admin.firestore.FieldValue.serverTimestamp()
    };

    // ログ用のドキュメントを作成する
    const docRef = admin.firestore().collection('collection').doc(context.params.docId).collection('logs').doc();
    
    // ログ用のドキュメントにデータを書き込む
    return docRef.set(logData)
      .then(() => {
        console.log('Log document created');
        return null;
      })
      .catch((error) => {
        console.error('Error creating log document:', error);
        return null;
      });
  });

ドキュメントIDの取得方法は以下です。

exports.myFunction = functions.firestore
  .document('collection/{docId}/subcollection/{subId}')
  .onCreate((snap, context) => {
    // これ
    const docId = context.params.docId;
    const subId = context.params.subId;
    console.log(`New subcollection created with ID: ${subId} in document with ID: ${docId}`);
  });
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?