Home > front end >  How to get the data of a user who created a document
How to get the data of a user who created a document

Time:08-08

I have two collections, one for registering properties and one for registered users.

The collection for registering properties is called listings and the collection for registered users is called users.

I access the documents inside the listings collection using the parameter listingId, which is the document ID.

I get the data from the document via the parameter I passed in:

const fetchListing = async () => {
    const docRef = doc(db, 'listings', listingId)
    // response
    const docSnap = await getDoc(docRef)

    if (docSnap.exists) {
        listing = docSnap.data()
    }   
}

I need to get the fields (name,email, twitter, etc..) of the user who created the document. How do I do this?

Each document has the ID of the user who creates it.

enter image description here

CodePudding user response:

You have to do as follows:

  1. Use the Object returned by the data() method, to get the user ID value (As explained in the doc, "this method retrieves all fields in the document as an Object").
  2. Get the document corresponding to this user ID (exactly as you do to get the listing doc) and then, get the data of this document (again with the data() method).

  const fetchListing = async () => {
    const docRef = doc(db, 'listings', listingId);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists) {
      const userId = docSnap.data().user;

      const userDocRef = doc(db, 'users', userId);
      const userDocSnap = await userDocRef(docRef);

      if (userDocSnap.exists) {
        const userName = docSnap.data().name;
        const userEmail = docSnap.data().email;
        // ...
      }
    }
  };

Note that a common approach for your use case in the NoSQL world is to denormalize your data in such a way that you get all the necessary data in your front-end in a minimum number of queries. Here is a "famous" post about NoSQL data-modeling approaches.

More concretely it means that in each Listing doc you would duplicate the data of its author/creator.

One side effect of this approach is that you need to keep the values in sync (i.e. the one in the User document and the ones in the Listing documents). This synchronization could be done with a Cloud Function triggered if the User doc is modified.

  • Related