0

This is how my firebase database looks like

This is how my firebase database looks like

How can I get all orders data from this database ?

This is how I have stored data :

db
    .collection('users')
    .doc(user?.email)
    .collection('orders')
    .doc(paymentIntent.id)
    .set({
        basket: basket,
        amount: paymentIntent.amount,
        created: paymentIntent.created
    })

setSucceeded(true);
setError(null);
setProcessing(false);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

1

You need to fetch initial collection snapshot and then get all subcollections.

If you're querying for a specific doc you can get a direct query result straight away:

const id = 123 // 'replace with whatever user you're trying to query'
const userOrders = await firebase.collection('users').doc(id)
 .collection('orders').get()
 .then(doc => doc.exists ? doc.data() : null)

Otherwise you'll need to perform two consequentive fetches

const ordersSnapshot = await firebase.collection('users').get()
const allOrders = await Promise.all(ordersSnapshot.docs.map(async ({ id }) => (
  firebase.collection('users').doc(id).collection('orders').get()
    .then(doc => doc.exists ? doc.data() : null)
)))
Samuel Hulla
  • 6,617
  • 7
  • 36
  • 70
  • useEffect(() => { if (user) { db .collection('users') .doc(user?.email) .collection('orders') .orderBy('created', 'desc') .onSnapshot(snapshot => ( setOrders(snapshot.docs.map(doc => ({ id: doc.id, data: doc.data() }))) )) } else([]) }, [user]) – Abhi Prajapati Sep 14 '21 at 12:04
  • This is how I fetched data for only one doc so now what changes should I make in my code to get data from all docs ? – Abhi Prajapati Sep 14 '21 at 12:05
1

Using Collection Group Queries might be the easiest way which fetches all documents from collections with same name which is passed in collectionGroup() method:

db.collectionGroup("orders").get().then((querySnapshot) => {
  console.log(querySnapshot.docs.map(d => ({id: d.id, ...d.data()})))
})

This will log an array of all orders.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84