【问题标题】:Firebase firestore won't persist arrayFirebase Firestore 不会持久化数组
【发布时间】:2020-08-30 05:15:00
【问题描述】:

我有一个云功能,可以处理和存储发送给它的数据。大多数数据都来自请求,除了我存储在我正在使用的主集合中以供参考的一些 ID 值。我的问题是我从其他云 Firestore 集合中获得的数据没有保留在我正在写入的集合中。我的代码如下所示:

await emails.forEach(async (email: string) => {
    try {
        // This should only ever return one result
        const student = await usersRef.where('userEmail', '==', email).get();
        if (student.empty) {
            console.log(`No matching documents for email: ${email}`);
        } else {
            student.forEach((s) => {
                const studentData = s.data();
                console.log('found student: ', studentData);
                // StudentIds stores reference to student objects
                studentIds.push(studentData.playerUniqueID); 
            });
        }
    } catch (err) {
        console.log('Error finding students: ', err);
        throw new functions.https.HttpsError('internal', 'Error finding students');
    }
});

const sessionId = uuidv4();
const newSession: newSessionWriteRequest = {
    emails, // emails is also an array of strings and is persisted properly
    owner,
    // StudentIds is not empty at this point and is populated correctly. StudentIds is an array of strings
    studentIds,
    ongoing: true,
    sessionName: data.sessionName,
    startTime: data.sessionStartDate,
    sessionId
};

try {
    // All values except studentIds are persisted to the sessionsRef except studentIds, which is a blank array
    await sessionsRef.doc(sessionId).set(newSession);
    console.log('new session: ', newSession);
    return newSession;
} catch (err) {
    console.log('Error creating new session: ', err);
    throw new functions.https.HttpsError('internal', 'Error creating new session');
}

StudentIds 只是一个字符串数组。 emails 也是一个字符串数组,但存储正确。两者之间的唯一区别是emails 来自对函数的初始请求,而studentIds 来自firestore。我的问题是为什么studentIds 没有被正确持久化?我不知道的 Firebase 集合之间是否存在某种交互?

【问题讨论】:

  • 您如何确定评论中的“StudentIds 不是空的”?在代码中的特定点,您的日志行在哪里证明它?鉴于当时代码的异步特性,forEach 中的日志行不足以证明这一点。
  • 当我注销newSession 对象时,我可以清楚地看到studentIds 数组已被填充。另外,为什么 forEach 循环中的 console.logs(假设您正在谈论循环 emails 的那个)不可靠?我在函数调用前面有一个await
  • forEach 不返回承诺,所以你不能真正等待它。 await 实际上什么都不做,forEach 之后的代码将在循环中的异步工作完成之前执行。请编辑问题以显示您的日志记录方式以及日志输出的内容。
  • Doug 提到的确实是正确的,它没有持续存在的原因是 StudentIds 可能没有正确填充,因为在您到达 newSession 部分时未解决承诺在您的代码中,尝试使用for ... of 而不是foreach,正如community answer 中提到的那样,让我知道它是否有效。
  • 现在我再看一遍,我认为你们是对的!感谢您的帮助!

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


【解决方案1】:

问题在于这段代码:

await emails.forEach(async (email: string) => {
    try {
        // This should only ever return one result
        const student = await usersRef.where('userEmail', '==', email).get();
        if (student.empty) {
            console.log(`No matching documents for email: ${email}`);
        } else {
            student.forEach((s) => {
                const studentData = s.data();
                console.log('found student: ', studentData);
                // StudentIds stores reference to student objects
                studentIds.push(studentData.playerUniqueID); 
            });
        }
    } catch (err) {
        console.log('Error finding students: ', err);
        throw new functions.https.HttpsError('internal', 'Error finding students');
    }
});

正如 cmets 中所指出的,我在 forEach 循环前面的 await 什么也没做。将其更改为此解决了问题:

const studentIds: string[] = await getStudentPlayerUniqueIds(emails);
...
const getStudentPlayerUniqueIds = async(emails: string[]): Promise<string[]> => {
  const studentIds: string[] = []
  try {
    for (const email of emails) {
      const student = await usersRef.where('userEmail', '==', email).get();
      if (student.empty) {
        console.log(`No matching documents for email: ${email}`);
      } else {
        student.forEach((s) => {
          const studentData = s.data();
          console.log('found student: ', studentData);
          studentIds.push(studentData.playerUniqueID);
        });
      }
    }
    return studentIds;
  } catch (err) {
    console.log('Error finding students: ', err);
    throw new functions.https.HttpsError('internal', 'Error finding students');
  }
}

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2017-06-16
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多