user9969622
user9969622

Reputation:

How to store a Firestore collection into a variable and then access docs inside it with Javascript?

I'm very happy that you are reading since I couldn't find an answer anywhere.The thing is I'm building an app with firestore which has two collections: Users and Offers. Previously I was doing

   db.collection("users").doc(firebaseUser.uid)
        .get()
        .then( doc => {
                let username = doc.data().user_name
         )}

every time I needed to access data for a user and same for offers. But I realised it would be better to get all the data at once, put it in an object and then look it up there. Since firestore doesn't let you fetch all the first level collections at once I created a new collection called "MyAppName" with documents "users" and "offers" inside of it, so I moved everything down one level. Then I tried doing

  db.collection("MyAppName")
  .get()
  .then(doc => {
   let username = doc.doc("users").collection(firebaseUser.uid).data().user_name;
   })

But doc.doc is not a function. When I do

          console.log(doc.data())

It isn't a function either, but when I do

          console.log(doc.docs.map(docs => docs.data()))

it returns

       (2) [{…}, {…}]
       0:
       1: {offer_type: "Product"}
       __proto__: Object
       1:
       user_name: "Ale"
       __proto__: Object
       length: 2

This has been a real pain in the back. My app runs perfectly the other way but I want to make it load the data only once since the api is pretty slow and also firestore charges based on requests. Any Help will be very appreciated :)

Edit: My database structure is

        MyAppname
                 |
                  users
                 |     |
                 |      user_name
                 |
                  offers
                        |
                         offer_type

Upvotes: 0

Views: 88

Answers (1)

user9969622
user9969622

Reputation:

I solved it, the way to do it was

    const dataobject = doc.docs.map(docs => docs.data())
    let users = (dataobject[1])
    let offers = (dataobject[0])

Then just handle users and offers with object methods.

Upvotes: 1

Related Questions