简体   繁体   中英

Firebase firestore won't persist array

I have a cloud function that processes and stores data sent to it. Most of the data comes from the request except for some ID values I store in the main collection I am working with for reference. My problem is the data I get from the other cloud firestore collection is not persisted in the collection I am writing to. My code looks like this:

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 is just an array of strings. emails is also an array of string but is stored correctly. The only difference between the two is that emails comes from the initial request to the function whereas studentIds comes from firestore. My question is why is studentIds not being persisted correctly? Is there some kind of interaction between firebase collections I am not aware of?

The issue lied with this block of code:

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');
    }
});

As pointed out in the comments, my await in front of the forEach loop was doing nothing. Changing it to this fixed the issue:

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');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM