0

I am creating a React Web Application. And I want to transform a firebase collection with documents into an array of objects. Every object in the array corresponding to a document in the collection. It would make my life easier. The reason why I'm asking is that i haven't been able to find a solution that works with Firebase Version 9.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Isso
  • 29
  • 1
  • 3
  • 1
    What have you tried? You say that "The reason why I'm asking is that i haven't been able to find a solution that works with Firebase Version 9.". Did you succeed with V8? – Renaud Tarnec Sep 06 '22 at 05:40
  • If you check the [documentation](https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection), you can use `getDocs()` to get a QuerySnapshot and then use `const arr = querySnapshot.docs.map((d) => ({ id: d.id, ...d.data() }))`. Is that what you are looking for? – Dharmaraj Sep 06 '22 at 05:41
  • @RenaudTarnec No i actually haven't tried with Firebase V8, but it would be nice to have the newest version of Firebase. – Isso Sep 06 '22 at 05:42
  • But did you try something? It would be nice to see what you have tried. – Renaud Tarnec Sep 06 '22 at 05:43
  • I think @Dharmaraj 's solution is the best way to go – edvilme Sep 06 '22 at 05:53

1 Answers1

5

You can use getDocs() with your CollectionReference or a Query and then map an array from the QuerySnapshot received as shown below:

const q = collection(db, "users")
const querySnapshot = await getDocs(q) 

const arr = querySnapshot.docs.map((d) => ({ id: d.id, ...d.data() }))

Checkout the documentation for more information.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84