首页 > 解决方案 > 无法读取 FireStore 函数中未定义的属性“userId”

问题描述

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

我的日志中的错误:

类型错误:无法在 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

那些没有用。

标签: angulartypescriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


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


推荐阅读