Skip to content

Instantly share code, notes, and snippets.

@carlosazaustre
Created October 23, 2020 15:09
Show Gist options
  • Save carlosazaustre/32097e9ba1ce7b2dae7a718a3ac11ef4 to your computer and use it in GitHub Desktop.
Save carlosazaustre/32097e9ba1ce7b2dae7a718a3ac11ef4 to your computer and use it in GitHub Desktop.
Get Data from nested collection on Firestore
// Database format: /products/{productId}/prices/{priceId}
export async function getProductPricesById(id) {
const prices = []
const snapshot = await DataSource.collection('products')
.doc(id)
.collection('prices')
.get()
snapshot.forEach((doc) => {
prices.push({ id: doc.id, data: doc.data() })
})
return prices
}
export async function getAllProducts() {
const products = []
const snapshot = await DataSource.collection('products')
.where('active', '==', true)
.get()
const productsResolved = await Promise.all(
snapshot.docs.map(async (doc) => {
const product = {}
product.id = doc.id
product.data = doc.data()
const productPrices = await getProductPricesById(product.id)
product.prices = productPrices
products.push(product)
return products
})
)
return productsResolved.length > 0
? productsResolved[productsResolved.length - 1]
: []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment