我在firebase实时数据库机智字段中有一个用户表:
userKey
- uid
- emailVerfied
- attempts
我想观察userKey/attempts
字段中的更改,我有以下触发设置:
export const onUpdate = functions.database
.ref('/users/{uid}/attempts').onUpdate( event => {
const record = event.after.val();
// sending an email to myself,
adminLog(
`user ${record.email} requested a new confirmation email`
, `delivered from realtime.onUpdate with user ${record.uid}`);
})
每次更新字段attempt
时都会触发此功能,但显然无法按照我的意图检索record.uid
,因为发送的电子邮件如下所示:
delivered from realtime.onUpdate with user undefined
检索数据库值的快照的正确方法是什么?
答案 0 :(得分:2)
使用您当前的代码和数据结构,uid
中'/users/{uid}/attempts'
的值实际上为userKey
,而不是uid
的值userKey
{1}}。
要在云功能代码中获取此值,您应该
event.params.uid
因为您使用的Firebase SDK for Cloud Functions版本是< 1.0.0(见下文)
如果相反,您希望获得uid
的值而不是userKey
的值,则应该在上一级听取,如下所示:
export const onUpdate = functions.database.ref('/users/{userKey}').onUpdate(...) //I just changed, for clarity, to userKey, instead of uid
我建议您将代码升级到v1.0.0(请参阅文档here),然后执行以下操作:
functions.database.ref('/users/{userKey}').onUpdate((change, context) => {
const beforeData = change.before.val(); // data before the update
const afterData = change.after.val(); // data after the update
//You can then check if beforeData.attempts and afterData.attempts are different and act accordingly
//You get the value of uid with: afterData.uid
//You get the value of userKey (from the path) with: context.params.userKey
});