firebase - 如何为 Firestore 数据库调用 onwrite 事件侦听器函数?
问题描述
functions.firestore
.document('users/00QAGyS0NqFdDSS78E6r')
.onWrite(event => {
const commentId = event.params.commentId;
const postId = event.params.postId;
// ref to the parent document
const docRef = admin.firestore().collection('posts').doc();
// get all comments and aggregate
return docRef.collection('comments').orderBy('createdAt', 'desc')
.get()
.then(querySnapshot => {
// get the total comment count
const commentCount = querySnapshot.size
const recentComments = []
// add data from the 5 most recent comments to the array
querySnapshot.forEach(doc => {
recentComments.push( doc.data() )
});
recentComments.splice(5)
// record last comment timestamp
const lastActivity = recentComments[0].createdAt
// data to update on the document
const data = { commentCount, recentComments, lastActivity }
// run update
return docRef.update(data)
})
.catch(err => console.log(err) )
});
如何为 Firestore 数据库调用 onwrite 事件侦听器函数?
解决方案
当firestore和firebase的数据库发生任何变化时调用“onwrite”事件函数。
exports.eventTriggerUserData = functions.firestore
.document('users/{userId}')
.onWrite((change: any, context: any) => {
/* Get user Id on which action perform
const userId = context.params.userId; */
/* Get data new data after action perform */
const documentAfter = change.after.exists ? change.after.data() : null;
/* Get data old data before action perform */
const documentBefore = change.before.exists ? change.before.data() : null;
});
您必须在 firebase 上部署此功能,并在 firestore 中添加、更新和删除数据。
推荐阅读
- javascript - 来自 json 的数据未定义
- html - 容器不会散开物品
- node.js - 调试 TypeScript VS Code 时未绑定断点
- http - +HTTPACTION= 0,200,351 无法发布数据
- database - 关键值基准提示
- java - Java - 将值传递给构造函数而不一一输入值
- blackberry - NDK 工具无法解密新的 BBID 令牌
- amazon-web-services - 尝试通过 Terraform 部署 AWS lambda 函数时出错
- matlab - 函数TextBounds Matlab中的DrawformattedText错误
- r - 如何根据r中的条件获得差异