【问题标题】:Cannot read property 'userId' of undefined in FireStore Function无法读取 FireStore 函数中未定义的属性“userId”
【发布时间】:2023-03-03 17:04:01
【问题描述】:

在我的 Angular 项目中,我第一次在 Firebase 中使用 Google Cloud 功能,但在这一行遇到了问题:const userId = event.params.userId;

我的日志中有错误:

TypeError:无法读取未定义的属性“userId” 在exports.firestoreEmail.functions.firestore.document.onCreate.event (/user_code/index.js:16:32) 在 cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23) 在 cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20) 在 /var/tmp/worker/worker.js:733:24 在 process._tickDomainCallback (internal/process/next_tick.js:135:7)

如果我执行以下 const userId = "6j1lvREbZwFEfzzJxQg7"; 操作,效果会非常好。

const functions = require("firebase-functions");

    const admin = require("firebase-admin");
    admin.initializeApp();

    const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
    const SENDGRID_API_KEY =
      "SECRET API KEY";

    const sgMail = require("@sendgrid/mail");
    sgMail.setApiKey(SENDGRID_API_KEY);

    exports.firestoreEmail = functions.firestore
      .document("users/{userId}/followers/{followerId}")
      .onCreate(event => {
        const userId = event.params.userId;

        const db = admin.firestore();

        return db
          .collection("users")
          .doc(userId)
          .get()
          .then(doc => {
            const user = doc.data();

            const msg = {
              to: user.email,
              from: "hello@angularfirebase.com",
              subject: "New Follower",
              // text: `Hey ${toName}. You have a new follower!!! `,
              // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,

              // custom templates
              templateId: "d-c66513d40f0e4b79845f63d598df5e07",
              substitutionWrappers: ["{{", "}}"],
              substitutions: {
                name: user.displayName
                // and other custom properties here
              }
            };

            return sgMail.send(msg);
          })
          .then(() => console.log("email sent!"))
          .catch(err => console.log(err));
      });

我已尝试将其更改为以下内容:

event.userId
user.userId
event.data().userId

那些没有用。

【问题讨论】:

  • 你能 console.log(event) 并显示对象吗?

标签: angular typescript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

如果您查看文档:https://firebase.google.com/docs/functions/database-events onCreate 事件需要两个参数(事件和上下文),因此请尝试将您的代码更改为 .onCreate((event,context) =&gt; {...}),您应该能够通过 context.params.userId 访问 userId

【讨论】:

  • 哇!你是个天才!!非常感谢老兄!! angularfirebase.com/lessons/… 我按照本教程进行操作,但他们没有使用上下文。估计没更新
  • @PatricioVargas 是的,您的教程不是最新的,并且与 Cloud Functions 版本 1.0.0 中引入的更改不一致,请参阅此文档:firebase.google.com/docs/functions/beta-v1-diff
  • @RenaudTarnec 非常感谢 Renaud!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多