简体   繁体   中英

Firestore - How to get document ID after fetching document?

In my database from Firestore, each User has a sub-collection called Apps. I would like to create sub-URLs with the ID of each app. But I have no idea how to get the document ID of my Apps sub-collection. Maybe I have to use an onSnapshot() method, but I'm not sure how to use it in my situation.

Thanks for your help.

function AppList() {
  const [apps, setApps] = React.useState([]);

  React.useEffect(() => {
    const fetchData = async () => {
      const db = firebase.firestore();
      var user = firebase.auth().currentUser;

      if (user != null) {
        var uid = user.uid;
        const data = await db
          .collection("Users")
          .doc(uid)
          .collection("Apps")
          .get();
        setApps(data.docs.map(doc => doc.data()));
      }
    };
    fetchData();
  }, []);

  return (
    <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
      {apps.map(app => (
        <Col className="gutter-row" span={100}>
          <Card
            style={{ width: 300, marginTop: 16 }}
            actions={[
              <Button type="default" size="middle">
                <Link to={}>
                  <EditOutlined />
                  <span> Edit the app </span>
                </Link>
              </Button>
            ]}
          >
            <Meta title={app.appName} description={app.description} />
          </Card>
        </Col>
      ))}
    </Row>
  );
}

Your data.docs is an array of DocumentSnapshot objects. Each will have an id property with the ID of the document. If you want to add it to your state, try something like this:

setApps(data.docs.map(doc => { id: doc.id, ...doc.data()));

This should create a property id on each mapped object, along with the data from the other fields using the JavaScript spread operator.

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