【问题标题】:how to get a document from firestore using a function in typescript?如何使用打字稿中的函数从firestore获取文档?
【发布时间】:2020-09-27 06:45:28
【问题描述】:

我想从我的集合中获取用户信息,使用他们的 ID 向他们发送通知。这是我在 index.ts 中的函数

export const sendNotifications = functions.firestore
.document('messages/{groupId1}/{groupId2}/{message}')
.onCreate((snapshot, context) =>{
    console.log('Starting sendNotification Function');   
    const doc = snapshot.data();
    console.log(doc.content);
    console.log(getUserData(doc.idFrom))
    return true;
});

export async function getUserData(id: string){
    try {
        const snapshot = await admin.firestore().collection('users').doc(id).get();
        const userData = snapshot.data();
        if(userData){
            return userData.nickname;
        }       

    } catch (error) {        
        console.log('Error getting User Information:', error);
        return `NOT FOUND: ${error}`
    }
 }

从我的部署中,我收到控制台日志消息“正在启动 sendNotification 函数”,然后是实际的“doc.content”,然后是“getUserData(doc.idFrom)”的错误。

Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } } 

提前谢谢你!

【问题讨论】:

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


    【解决方案1】:

    您应该使用await 调用您的异步getUserData() 函数。

    以下应该可以解决问题(未经测试):

    export const sendNotifications = functions.firestore
      .document('messages/{groupId1}/{groupId2}/{message}')
      .onCreate(async (snapshot, context) => {
        try {
          console.log('Starting sendNotification Function');
          const doc = snapshot.data();
          console.log(doc.content);
    
          const nickname = await getUserData(doc.idFrom);
          // Do something with the nickname value
          return true;
        } catch (error) {
          // ...
        }
      });
    
    async function getUserData(id: string) {
      try {
        const snapshot = await admin.firestore().collection('users').doc(id).get();
        if (snapshot.exists) {
           const userData = snapshot.data();
           return userData.nickname;
        } else {
          //Throw an error
        }
      } catch (error) {
        // I would suggest you throw an error
        console.log('Error getting User Information:', error);
        return `NOT FOUND: ${error}`;
      }
    }
    

    或者,如果您不想让 Cloud Function 异步,您可以执行以下操作:

    export const sendNotifications = functions.firestore
      .document('messages/{groupId1}/{groupId2}/{message}')
      .onCreate((snapshot, context) => {
        console.log('Starting sendNotification Function');
        const doc = snapshot.data();
        console.log(doc.content);
    
        return getUserData(doc.idFrom)
          .then((nickname) => {
            // Do something with the nickname value
            return true;
          })
          .catch((error) => {
            console.log(error);
            return true;
          });
      });
    

    【讨论】:

    • 如何获取 {groupId2} 的值?
    • 只需使用context 对象:context.params.groupId2
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2019-11-27
    相关资源
    最近更新 更多