【问题标题】:retrieve Firestore document from onCreate trigger with Cloud Functions使用 Cloud Functions 从 onCreate 触发器中检索 Firestore 文档
【发布时间】:2021-07-21 01:31:22
【问题描述】:

创建另一个文档时,我需要从 Firestore 文档中检索信息。当我尝试这样做时,我遇到了关于函数不是异步的错误。我已经很久没有使用javascript了,我基本上又是一个新手,不知道如何解决这个问题。

好的,所以我正在使用 Firebase Cloud Functions,而有问题的函数是 Firestore .onCreate() 触发器。

当函数被触发时,我设置了一个 sender 变量(这是我需要检索的不同集合中的文档 ID)

然后我尝试按照文档获取文档。

函数最终是这样的:

exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
.onCreate((snap, context) => {
  // when friend request is created
  
  data = doc.data()//get request data
  sender = data["sender"]//get request sender from data
  
const requestRef = db.collection('User').doc(sender);
const doc = await requestRef.get();//get user data of sender
if (!doc.exists) {
    console.log('No such document!');
} else {
    console.log('Document data:', doc.data());
    
            
}
});

当我在模拟器中运行它时,我得到了这个错误:

const doc = await requestRef.get();//get user data of sender
            ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

我完全不知道从这里去哪里。

谁能帮我解决这个问题? 谢谢

【问题讨论】:

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


    【解决方案1】:

    如果您使用 await,您必须指定该函数为 asynchronous。否则会报错。

    exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}').onCreate(async (snap, context) => {
        // when friend request is created
        data = doc.data()//get request data
        sender = data["sender"]//get request sender from data
        const requestRef = db.collection('User').doc(sender);
        const doc = await requestRef.get();//get user data of sender
        if (!doc.exists) {
            console.log('No such document!');
        } else {
            console.log('Document data:', doc.data());      
        }
    });
    

    但我们不知道您的一些参考资料。也许这段代码没有完成。

    重点是你需要了解什么时候可以访问async/awaitPromise

    【讨论】:

      【解决方案2】:

      await 关键字仅在 async 函数中有效。

      exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
        .onCreate(async (snap, context) => {
              //  ^^^^^
        })
      

      如果您正在(或需要)使用同步功能,那么您必须使用promise chaining

      exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
        .onCreate((snap, context) => {
           return requestRef.get().then((snapshot) => {
             if (snapshot.exists) { ... }
           })
        })
      

      除此之外,变量/语句的顺序看起来不正确。使用当前代码(与原始问题一样),您最终可能会收到错误:“初始化之前无法访问 'doc'” 尝试像这样重构它:

      exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
        .onCreate(async (snap, context) => {
          // accessing data from newly created doc
          const newDocData = snap.data()
      
          // const sender = "" // ??
           
          const requestRef = db.collection('User').doc(sender);  
          const doc = await requestRef.get();//get user data of sender
          if (!doc.exists) {
            console.log('No such document!');
          } else {
            console.log('Document data:', doc.data());      
          }
        })
      

      sender 来自哪里?我刚刚在上面评论过,但如果发件人出现在新文档中,那么您可以通过以下方式访问它:const sender = newDocData.sender

      【讨论】:

      • 虽然这里的每个答案都给出了基本相同的答案,但我选择将您标记为正确,因为您发现了 doc.data() 错误(谢谢)....发件人确实出现在新的文档,我找不到有关访问文档中特定字段的文档(当时是凌晨 2 点,我很累哈).... P .....欢呼:)
      • @Andy 很高兴听到这个消息:D 查看此Firecast 以更好地了解 Firestore 触发器。 .sender["sender"] 也是一样的东西 (Property Accessor)。您的“文档”将是未定义的。
      【解决方案3】:

      所有 await 方法必须在异步块内或使用 .then()promises 在异步庄园中处理

      在这种情况下,父函数在这一行.onCreate((snap, context) => {

      只需在变量的开头插入 async 即可将箭头函数升级为异步箭头函数 .onCreate(async (snap, context) => {

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-05
        • 2021-04-13
        • 1970-01-01
        • 2021-03-16
        • 2018-03-27
        • 1970-01-01
        • 2019-01-25
        • 1970-01-01
        相关资源
        最近更新 更多