1

pic

firestore.collection("records").doc("12345")
        .onSnapshot(function(doc) {
            console.log("Current data: ", doc.data());

this code currently shows the name of the field and then what is in the field but only does so in the console. When I try and display it in the website it comes up with [object object].

I just want to be able to display the field name. Any suggestions? Thanks

I would like it to display

DOB: 26/03/18

age: 56

firstName: Joe

from: New York

job: builder

surname: Bloggs

Neesh
  • 57
  • 1
  • 7

2 Answers2

1

To loop over all fields in your document, you can use for example Object.keys():

firestore.collection("records").doc("12345").onSnapshot(function(doc) {
    let data = doc.data();
    Object.keys(data).forEach(function(key) {
      console.log(key+": "+data[key]);
    });
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

This only requires basic JavaScript manipulation of the object returned by data(). The object contains properties whose names and values come directly from the document in Firestore:

firestore.collection("records").doc("12345")
    .onSnapshot(function(doc) {
        let data = doc.data();
        // gets the value of a field called field1 from the doc
        let value1 = data.field1;
    })
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks, but if I have a lot of fields in a collection how can I display all of the field names and the values – Neesh Dec 08 '18 at 23:21
  • without writing every single field name? – Neesh Dec 08 '18 at 23:36
  • Access them all using the code I showed. Since I don't know all the fields and what you want to do with them, it's seems a bit vague to me. – Doug Stevenson Dec 08 '18 at 23:36
  • I have added a picture of the database and how I would like it to look. Hope this helps you to find a answer, just click the pic link at the top – Neesh Dec 08 '18 at 23:55
  • It seems like you have everything you need to make an attempt at this on your own. Stack Overflow is not really a place to get someone to write the code for your app. – Doug Stevenson Dec 09 '18 at 00:05
  • Really sorry but just want to know if I can display the field names in a collection without having to manually type them into the code – Neesh Dec 09 '18 at 00:37
  • Yes, just iterate the properties of the object. https://stackoverflow.com/questions/8312459/iterate-through-object-properties – Doug Stevenson Dec 09 '18 at 00:51