简体   繁体   中英

How to use an array of keys to query multiple documents in Firestore

I have a website where users can do courses. When a user starts a course, I want to add the course identifier to that users document in firestore. On the website, the user has their own profile page. One of the sections there is a courses in progress section, where users can see the course that they are currently enrolled in.

I am able to add the course document key to a field on the user's document once they start the course, the field is an array of strings containing keys to documents in another collection.

The issue Im having is trying to display the courses that the user is currently enrolled in on their profile.

I think the problem is that the course documents are coming back after the screen is rendered.

I have tried using async and await, to make sure the code completes the loop first and gets all course document, so it can then render them to the screen, but that's not working.

Thanks very much in advance for any help

getEnrolledCareersList = async () => {

  let careersEnrolled = [];
  let careersEnrolledTemp = [];
  let careersEnrolledDocumentKeys = ["84YU2pLABF6qUvUEuwIm", "kwBaAUwkjTutGTcIKShw"];

 await careersEnrolledDocumentKeys.forEach((documentKey) =>{

      console.log("documentKey: ", documentKey);

      db.collection("...")
          .where("courseDocumentKey", "==", documentKey)
          .get()
          .then(
              (querySnapshot) => {
                  if (querySnapshot.empty) {
                      // doc.data() will be undefined in this case
                      console.log("No such document!");
                      return;
                  }

                  querySnapshot.forEach((doc) => {
                      console.log("getEnrolledCareersList Document data:", doc.data());
                      const {
                          courseName,
                          courseId,
                          coursePhotoUrl,
                          courseDocumentKey,
                      } = doc.data();

                      careersEnrolledTemp.push({
                          courseName,
                          courseId,
                          coursePhotoUrl,
                          courseKey: courseDocumentKey,
                      });
                  });
              },
              function(error) {
                  console.log("Error getting document Error: ", error);
              },
          );

  });

JSX Component:

<div
          style={{
            // border: "solid #8492A6 5px",
            display: "flex",
            flexDirection: "column",
            //flexWrap: "wrap",
            justifyContent: "flex-start",
            padding: "0 0%",
          }}>

          {this.state.currentPaths.map((item, index) => (
            <div
              style={{
                display: "flex",
                flexDirection: "row",
                padding: "1% 1%",
              }}>
              <img
                alt={"career image"}
                src={item.coursePhotoUrl}
              />
              <div
                style={{
                    // border:"solid red 1px",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "space-evenly",
                  padding: "0 2%",
                }}>

                  {/*Career Name Label*/}
                <label
                  style={{
                    // border: "solid  #8492A6",
                    textAlign: "center",
                  }}>
                  {item.courseName}
                </label>

                  {/*Career Percentage Completed Label*/}
                <label
                  style={{
                    // border: "solid  #8492A6",
                    textAlign: "center",
                  }}>
                  Percentage
                </label>
              </div>
            </div>
          ))}
        </div>

I ended up doing this and it solved my problem. A friend helped me get this, as well as @Doug Stevenson thanks very much.

getCourse = id => db.collection("abc")
    .doc(id)
    .get();

getEnrolledCareersList = async (courseIds = ["1", "2"]) => {
  const requests = courseIds.map(this.getCourse);
  const responses = await Promise.all(requests);
  const enrolledCourses = responses.map(doc => doc.data());
  this.setState({
      ...this.state,
      enrolledCourses,
  });
};

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