How to add timestamp to every collection insert,update in Cloud Functions for firestore database

别说谁变了你拦得住时间么 提交于 2019-12-29 08:04:33

问题


I have a firestore collection called Posts I make an insert on the client side and it works.

I want to add the createdAt and updatedAt fields to every insert in my posts collection firestore using firebase functions.


回答1:


In order to add a createdAt timestamp to a Post record via a Cloud Function, do as follows:

exports.postsCreatedDate = functions.firestore
  .document('Posts/{postId}')
  .onCreate((snap, context) => {
    return snap.ref.set(
      {
        createdAt: admin.firestore.FieldValue.serverTimestamp()
      },
      { merge: true }
    );
  });

In order to add a modifiedAt timestamp to an existing Post you could use the following code. HOWEVER, this Cloud Function will be triggered each time a field of the Post document changes, including changes to the createdAt and to the updatedAt fields, ending with an infinite loop....

exports.postsUpdatedDate = functions.firestore
  .document('Posts/{postId}')
  .onUpdate((change, context) => {
    return change.after.ref.set(
      {
        updatedAt: admin.firestore.FieldValue.serverTimestamp()
      },
      { merge: true }
    );
  });

So you need to compare the two states of the document (i.e. change.before.data() and change.after.data() to detect if the change is concerning a field that is not createdAt or updatedAt.

For example, imagine your Post document only contains one field name (not taking into account the two timestamp fields), you could do as follows:

exports.postsUpdatedDate = functions.firestore
  .document('Posts/{postId}')
  .onUpdate((change, context) => {
    const newValue = change.after.data();
    const previousValue = change.before.data();

    if (newValue.name !== previousValue.name) {
      return change.after.ref.set(
        {
          updatedAt: admin.firestore.FieldValue.serverTimestamp()
        },
        { merge: true }
      );
    } else {
      return false;
    }
  });

In other words, I'm afraid you have to compare the two document states field by field....




回答2:


You do not need Cloud Functions to do that. It is much simpler (and cheaper) to set server timestamp in client code as follows:

var timestamp = firebase.firestore.FieldValue.serverTimestamp()   
post.createdAt = timestamp
post.updatedAt = timestamp


来源:https://stackoverflow.com/questions/52660962/how-to-add-timestamp-to-every-collection-insert-update-in-cloud-functions-for-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!