【问题标题】:update firestore document with cloud functions使用云功能更新 Firestore 文档
【发布时间】:2019-08-07 18:22:10
【问题描述】:

您好,我正在尝试使用云功能更新 Firestore 中的文档,但我对云功能如何知道要更新的文档是我的代码感到困惑

云函数代码

exports.newsletterGreetConfirm = functions.firestore
  .document('newsletter/{newsletterId}')
  .onUpdate((change, context) => {
    const newValue = change.after.data();
    console.log(newValue);
    return 0;
  });

在我的云函数 shell 中将以下对象传递给我的 newsletterGreetConfirm 函数

{email:"test@gmail.com",id:"LgNqtD6Ih7SYPEEz8jJl",subscribedToNewsletterList:true,timestamp:12321312}

我的输出是undefined
我的目标是在用户单击确认电子邮件中的按钮或链接时确认电子邮件地址。只是在构建此功能的第一阶段感谢所有帮助!我也在使用react

【问题讨论】:

    标签: node.js reactjs firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    这个想法是要么通过电子邮件中发送的 URL 直接向 firebase 生成 HTTP 请求,要么通过 React 进行。

    您可以将它们发送到 URL example.com/verify/USER_DOC_ID

    假设您使用react-router-dom,并且您希望使用 web firebase API 来避免创建 HTTP 请求,您可以在您的 React 组件中执行以下操作(这也假设您在 React 中正确使用了 firestore):

    import React, {Component} from 'react':
    import firestore from './firestore'; //this is your config file
    import {withRouter} from 'react-router-dom';
    
    
    class Verify extends Component {
    
        componentDidMount(){
            const {pathname} = this.props.location;
            const ID = pathname.split('/')[2];
            //DO THE FIREBASE UPDATE HERE
         }
         render(){...}
    
    
    export default withRouter(Verify);
    

    现在,对于我放置 //DO THE FIREBASE UPDATE HERE 的位置,您有几个选择。您可以向 firebase 创建一个 http 请求,也可以使用 web 端 firebase。如果您使用的是 web 端 firebase,您只需更新 firebase 中的文档(请注意,如果您正在执行 fetch 请求,则无需在 react 中导入 firestore。)

    react 方式涉及到这样的事情:

    const ref = firebase.firestore().collection('newsletter').doc(ID);
    ref.get().then((doc) => {
        if(doc.exists()){
            ref.update({verified: true});
      });
    

    与 Firestore 交互的逻辑在后端与 Admin API 非常相似,但是您将其包装在云函数中的 HTTP 请求中:

    exports.verify = functions.https.onRequest((req, res) => {
      // admin api call with req params or body
    });
    

    使用上面的代码,您可以直接从电子邮件导航到此处,直接使用 HTML 回复,也可以通过 react 应用程序中的 fetch 请求调用它,例如 fetch("https://example.com/verify/ID").then(...)

    如果您想了解有关我描述的上述任何一种方法的更多详细信息,如果您在 SO 上找不到它,请将其作为单独的问题发布,请告诉我,我会尽力回答。

    【讨论】:

    • @helloworld 这里是一个教程的链接,你可以通过 react 来查看 firestore:hackernoon.com/…
    • 请注意,您还需要配置数据库规则并下载配置文件。您可能应该首先下载配置文件(firebase 使这部分变得容易),并且只在最后的手段下调整数据库规则。如果您使用云功能,则无需搞砸这些步骤。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2020-08-02
    • 2018-05-19
    • 2019-12-13
    • 2018-12-15
    • 2020-01-24
    相关资源
    最近更新 更多