如何为每个集合插入添加时间戳,如何在Cloud Functions中更新Firestore数据库 [英] How to add timestamp to every collection insert,update in Cloud Functions for firestore database
问题描述
我有一个名为Posts的Firestore集合 我在客户端插入了一个插件,就可以了.
I have a firestore collection called Posts I make an insert on the client side and it works.
我想使用firebase函数将createdAt和updatedAt字段添加到我的帖子集合firestore中的每个插入中.
I want to add the createdAt and updatedAt fields to every insert in my posts collection firestore using firebase functions.
推荐答案
要通过Cloud Function向Post
记录添加createdAt
时间戳,请执行以下操作:
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 }
);
});
为了将modifiedAt
时间戳添加到现有的Post
,您可以使用以下代码. 但是,每次发布文档的某个字段发生更改(包括对createdAt
和updatedAt
字段的更改,以无限循环结束)时,都会触发此Cloud Function. strong> ....
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 }
);
});
因此,您需要比较文档的两种状态(即change.before.data()
和change.after.data()
),以检测更改是否涉及的字段不是createdAt
或updatedAt
.
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
.
例如,假设您的Post文档仅包含一个字段name
(不考虑两个时间戳字段),则可以执行以下操作:
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....
这篇关于如何为每个集合插入添加时间戳,如何在Cloud Functions中更新Firestore数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!