Created
October 23, 2020 15:09
-
-
Save carlosazaustre/32097e9ba1ce7b2dae7a718a3ac11ef4 to your computer and use it in GitHub Desktop.
Get Data from nested collection on Firestore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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