云函数上下文参数返回未定义

时间:2018-12-15 11:59:29

标签: google-cloud-firestore google-cloud-functions

我正在使用云功能来侦听在Firestore上创建的新文档。

functions.firestore.document('users/{userId}')
        .onCreate((snapshot, context) => {
            console.log('params', context.params.userId);
});

日志显示 未定义 ,而不是通配符。

此活动从2018年12月15日午夜开始。

这是与Firestore / Cloud功能更新有关的错误吗? 以及我们如何绕过这个问题?

2 个答案:

答案 0 :(得分:9)

当前(2018年12月15日),Firebase Functions SDK或平台似乎存在错误。

解决方法:

更新:访问父文档ID的正确方法是通过change.after.ref.parent.parent.idsnapshot.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。< / p>

答案 1 :(得分:3)

我是负责此事件的Google员工。当Firestore处于私有alpha版本且尚未升级时,使用SDK的客户会遇到一个已知的兼容性问题。

使用低于0.6.2的SDK版本较新运行其代码的受影响客户可以响应吗?如果您运行的是0.6.1版本,则可以升级到0.6.2,而无需进行任何代码更改即可解决。

相关问题