【问题标题】:Cloud Function Firestore trigger for document at any level to set createdAt任何级别的文档的 Cloud Function Firestore 触发器以设置 createdAt
【发布时间】:2020-10-13 17:50:41
【问题描述】:

我想在我的 Firestore 数据库中的任何级别创建或更新文档时相应地设置 createdAtupdatedAt

看来wildcards 不支持多级,所以我最终编写了这样的代码(对于createdAt):

exports.onDocCreate = functions.firestore
  .document("{collection}/{docId}")
  .onCreate((snap, context) => {
    const { collection, docId } = context.params;
    return db.collection(collection).doc(docId).set(
      {
        createdAt: admin.firestore.Timestamp.now(),
      },
      { merge: true }
    );
  });

exports.onSub1DocCreate = functions.firestore
  .document("{c0}/{d0}/{c1}/{d1}")
  .onCreate((snap, context) => {
    const { c0, d0, c1, d1 } = context.params;
    return db.doc(`${c0}/${d0}/${c1}/${d1}`).set(
      {
        createdAt: admin.firestore.Timestamp.now(),
      },
      { merge: true }
    );
  });

exports.onSub2DocCreate = functions.firestore
  .document("{c0}/{d0}/{c1}/{d1}/{c2}/{d2}")
  .onCreate((snap, context) => {
    const { c0, d0, c1, d1, c2, d2 } = context.params;
    return db.doc(`${c0}/${d0}/${c1}/${d1}/${c2}/${d2}`).set(
      {
        createdAt: admin.firestore.Timestamp.now(),
      },
      { merge: true }
    );
  });

这涵盖了 3 个级别,我可以继续使用相同的模式来支持我需要的任何级别。

有没有更好的办法?

【问题讨论】:

    标签: google-cloud-firestore google-cloud-functions


    【解决方案1】:

    假设 .document("{c0}/{d0}/{c1}/{d1}").document("{c0}/{d0}/{c1}/{d1}") 是子集合,那么通配符应该是:

    这里是github

    function multiWildcard() {
      // [START multi_wildcard]
      // Listen for changes in all documents in the 'users' collection and all subcollections
      exports.useMultipleWildcards = functions.firestore
          .document('users/{userId}/{messageCollectionId}/{messageId}')
          .onWrite((change, context) => {
            // If we set `/users/marie/incoming_messages/134` to {body: "Hello"} then
            // context.params.userId == "marie";
            // context.params.messageCollectionId == "incoming_messages";
            // context.params.messageId == "134";
            // ... and ...
            // change.after.data() == {body: "Hello"}
          });
      // [END multi_wildcard]
    }
    

    在示例中:

    监听“用户”集合和所有子集合中所有文档的变化

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 2020-01-02
      • 2019-01-16
      • 2021-04-06
      相关资源
      最近更新 更多