gpt4 book ai didi

firebase - 所有文档的通用 Firestore 触发器

转载 作者:行者123 更新时间:2023-12-04 16:28:33 24 4
gpt4 key购买 nike

如何触发 Firestore 中任何集合中的任何文档更改的函数?我想管理 createdAtupdatedAt 时间戳。我有很多集合,不想为每个集合单独注册触发器。那时我还不如为 addsetupdate 创建包装函数。

如何注册一个在任何文档被修改时触发的回调?

编辑:

此时(2019-08-22),我决定只创建一个包装函数来实现此功能。接受的答案不保持模式少。基于 this article ,我创建了这个 upset 函数来管理时间戳并避免“文档不存在”错误:

const { firestore: { FieldValue } } = require('firebase-admin')

module.exports = async function upset (doc, data = {}) {
const time = FieldValue.serverTimestamp()

const update = { updatedAt: time }
const updated = { ...data, ...update }

try {
const snapshot = await doc.get()

if (snapshot.exists) {
return doc.update(updated)
} else {
const create = { createdAt: time }
const created = { ...updated, ...create }

return doc.set(created)
}
} catch (error) {
throw error
}
}

最佳答案

doc 中所述,您可以在文档路径中使用通配符。更具体地说,“您可以定义任意数量的通配符来替换显式集合或文档 ID”

因此,以下 Cloud Function 将适用于根集合下的文档:

exports.universalFirestoreTrigger = functions.firestore
.document('{collecId}/{docId}')
.onWrite((snap, context) => {

console.log("Collection: " + context.params.collecId);
console.log("Document: " + context.params.docId);

return null;

});

如果有子集合,则需要再写一个Cloud Function,如下:

exports.universalFirestoreTriggerSubCollections = functions.firestore
.document('{collecId}/{docId}/{subCollecId}/{subDocId}')
.onWrite((snap, context) => {

console.log("Collection: " + context.params.collecId);
console.log("Document: " + context.params.docId);
console.log("Sub-Collection: " + context.params.subCollecId);
console.log("Sub-Collection Document: " + context.params.subDocId);

return null;

});

如果你有子子集合,依此类推......

关于firebase - 所有文档的通用 Firestore 触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57570202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com