0
votes

I tried to get my data from a Firestore database, there's a field with 'reference' data type, here's my data structure

guns collection

{
  "id":"...some id...",
  "name":"M4A1",
  "manufacturer":"Colt",
  "gun_type:"/gun_type/...some id..." (reference)
}

gun_type collection

{
  "id":"...some id...",
  "name":"Assault Rifle",
  "abbr":"AR"
}

I want to make the reference work like foreign key in SQL databases

Here's my code to fetch data from firestore

this.db.collection("gun").get().then((response)=>{
    let newRecords = []
    response.forEach((doc) => {
        let data = doc.data()
        // possible cause
        if (data.gun_type) {
            data.gun_type.get().then((res)=>{
                let gunType = res.data()
                newRecords.push({
                    id:doc.id,
                    gunType:gunType,
                    name:data.name,
                    manufacturer:data.manufacturer
                })
            })
        } else {
            newRecords.push({
                id:doc.id,
                name:data.name,
                manufacturer:data.manufacturer
            })
        }
    })
    this.setState({
        records:newRecords
    })
}).catch((error)=>{
    console.error(error)
})

Then I tried to show the records in a basic HTML table with map(), when I log the data before return statement in render(), the data is exists in this.state.records, but not showing in the table. There's no error logged in the console, When I remove codes related to gun_type reference, the data showing normally. Am I doing it wrong with reference data key? any answer will be appreciated.

sorry for my bad English

--Edit--
I noticed get() method for gun_type reference is also returns a promise, so I can't push objects with gun_type field to newRecords array. My current solution is to setState each objects directly to records state. I know it's not the best solution, but it's works. Any better solution?

1

1 Answers

0
votes

When you get() a collection or a query, it returns a group snapshot of multiple documents where each document is stored inside a docs property of which you can iterate through as needed. Simply adding .docs before your forEach can iterate through each document.

response.docs.forEach((doc) => {