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.
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.
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....
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