0

I am using Vue.js and Firebase Firestore. Now I have two collectionsusers and orders. In the orders collection, I have already stored the id of each document of user collection. I now have to fetch the details of the corresponding users from this. How am I supposed to go about it? This is what I've done so far

let orderRef = db.collection("orders")
orderRef.onSnapshot(snapshot => {
  snapshot.docChanges().forEach(change => {
    if (change.type == "added") {
      let doc = change.doc;
      this.orders.push({
        id: doc.id,
        orderData: doc.data().orderData,
        user_id: doc.data().user_id,
        userInfo: db.collection("users").doc(user_id),
      });
    }
  });
});

I need to store user data in userInfo.Thanks in advance

Manish B
  • 51
  • 1
  • 6

2 Answers2

1

Firestore doesn't support foreign key like SQL database, so you can't retrieve nested data like SQL.
In Firestore you need to fetch referenced data separately, either you can fetch all users data separately in parallel with orders data and store it in map, or if you don't need users data initially then fetch each users data when needed like when you check details of each order.

ked
  • 2,426
  • 21
  • 24
1

I think that you're structuring your data as if you were working in a relational database. Firestore is a no-SQL database that doesn't have any notion of reference, the only thing Firestore understands are key-values, documents and collections, everything else has to me modeled on top of that. See Firestore data model.

In Firestore relationships are usually modeled by storing the id of the document you'd like to "reference". In that sense you might not need to store the 'users' document inside the 'order' but the field 'user_id' would suffice. The caveat is that this data layout comes at the price of having to fetch the 'user_id' from orders before you can fetch the actual user data. You could read more about data denormalization and modeling relationships in articles link1, link2 and this other thread.

Also, it's worth noting that Firestore documents are limited in size to 1MB so with your actual configuration if the amount of info of 'user' documents increases it may get to a point where it would be necessary to reshape your documents structure.

All in all, if you don't want to change your data layout you would need to follow Ked suggestions and first retrieve the 'users' data to inline it into the 'userInfo' field.

Happy-Monad
  • 1,962
  • 1
  • 6
  • 13