google-cloud-firestore - 云函数上下文参数返回未定义

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

我正在使用云函数来监听在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.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的方法。

关于google-cloud-firestore - 云函数上下文参数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53792140/

相关文章:

javascript - 使用vuejs加载页面时如何从firebase获取数据?

android - 无法让 FirestoreRecyclerAdapter 显示项目

java - 使用 .toObject 和 Firestore 中的通用类从 DocumentSnapshot 获取 POJO

node.js - 设置 Firebase 本地模拟器云功能环境配置值

javascript - firebase Promise 使用节点 Firebase 函数在 foreach 中调用

node.js - Firebase 事务一次更新文档中的多个字段

java - 应用程序在检索值时不断崩溃

node.js - 如何在 firestore/nodejs 中存储/使用十进制和货币值

从 npm 安装的 firebase 部署和二进制文件?

google-cloud-functions - 将敏感信息传递给云功能