云函数context params返回undefined

iou*_*mmi 10 google-cloud-functions google-cloud-firestore

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

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

日志显示undefined而不是wildcarded param.

这个开始发生在2018年12月15日午夜.

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

rma*_*mac 9

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

解决方法:

更新访问父文档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...
  });
Run Code Online (Sandbox Code Playgroud)

对于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...
  });
Run Code Online (Sandbox Code Playgroud)

为了完整性并突出显示错误,这两个示例都显示了您通常如何从中提取ID context.params,然后添加解决方法以从快照/更改对象中提取ID.

  • 我甚至无法想象有多少生产系统因此而被打破......他们是否对此发表了任何声明? (4认同)
  • 很高兴我找到了.因此,今天我们身边的一切都被打破了. (2认同)