简体   繁体   English

如何使用一组键来查询Firestore中的多个文档

[英]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. 当用户启动课程时,我想将课程标识符添加到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. 我已经尝试使用async和await,以确保代码首先完成循环并获取所有课程文档,因此它可以将它们呈现到屏幕上,但这不起作用。

Thanks very much in advance for any help 非常感谢您的任何帮助

getEnrolledCareersList = async () => { 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: JSX组件:

<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. 一位朋友帮助我得到了这个,以及@Doug Stevenson非常感谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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