【问题标题】:Executing if statement using cloud functions使用云函数执行 if 语句
【发布时间】:2020-06-17 12:23:02
【问题描述】:

尝试对文档数据的 done 元素是否为真进行基本检查。

exports.watchTodos = functions.firestore.document('users/{uid}/todos/{docId}')
        .onUpdate(async (snap, context) => {
            if(snap.after.data().done){ 
            console.log('is done') 
        },
}

但是 console.log 永远不会执行,但是如果我记录 snap.after.data().done 它会返回 true。

【问题讨论】:

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


    【解决方案1】:

    假设 done 是文档中的布尔字段类型,您可以执行以下操作:

    exports.watchTodos = functions.firestore.document('users/{uid}/todos/{docId}')
            .onUpdate( (snap, context) => { 
    
          // Retrieving uid from the paramaters. 
          const uid = context.params.uid;            
    
          // TODO: retrieve the done field from the document     
          return admin.firestore().collection("users")
          .doc(`${uid}`)
          .get()
          .then(doc => {
    
            // Data contains all the fields within your document.
            const data = doc.data();
            // Accessing the phone property.
            const isDone = data.done;
    
            return console.log(isDone); 
    
          })
          .catch(err => console.error(err))
      );
    
    })
    

    不要忘记查看documentation 和其他 Stackoverflow 帖子以获取更多示例。

    【讨论】:

    • 代码编辑器出现错误提示:Object is possible 'undefined'.ts(2532) when data.done is called
    • 我试过 const isDone = data?.done;当我尝试部署它时,错误是:错误:函数预部署错误:命令以非零退出代码终止
    • 我正在使用打字稿
    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2023-01-20
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多