我正在使用云函数来监听在Firestore上创建的新文档。
functions.firestore.document('users/{userId}')
.onCreate((snapshot, context) => {
console.log('params', context.params.userId);
});
日志显示 undefined 而不是通配符。
此事件从2018年12月15日午夜开始。
这是与Firestore/Cloud功能更新有关的错误吗?
以及我们如何绕过这个问题?
最佳答案
当前(2018年12月15日),Firebase Functions SDK或平台中似乎存在一个错误。
解决方法:
更新访问父文档ID的正确方法是通过change.after.ref.parent.parent.id
或snapshot.ref.parent.parent.id
。注意 .parent.parent
。
如果期望带有文档ID的参数,则可以通过使用函数的第一个参数中提供的数据来解决此问题。
这是一个带有onCreate
触发函数的示例:
export const myCreateTriggeredFn = firestore
.document("user/{userId}/friends/{friendId}")
.onCreate((snapshot, context) => {
let { userId, friendId } = context.params;
if (typeof userId !== "string" || typeof friendId !== "string") {
console.warn(`Invalid params, expected 'userId' and 'friendId'`, context.params);
userId = snapshot.ref.parent.parent.id;
friendId = snapshot.id;
}
// Continue your logic here...
});
对于
onWrite
触发的函数:export const myChangeTriggeredFn = firestore
.document("user/{userId}/friends/{friendId}")
.onWrite((change, context) => {
let { userId, friendId } = context.params;
if (typeof userId !== "string" || typeof friendId !== "string") {
console.warn(`Invalid params, expected 'userId' and 'friendId'`, context.params);
userId = change.after.ref.parent.parent.id;
friendId = change.after.id;
}
// Continue your logic here...
});
为了完整起见并突出显示该错误,两个示例都展示了通常如何从
context.params
提取ID,然后添加了解决方法从快照/更改对象提取ID的方法。
关于google-cloud-firestore - 云函数上下文参数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53792140/