Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase: Why does my Code only use the first documet in my Collection?

I hope somebody can help me, I am searching for hours 🙁

The Problem on this Code is that in the log file of Firebase there only stands:

"after for each =undefinedsensor_location_1undefinedundefinedundefined "

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so why does he only use the first document (in this case it is location_id wich is the first document for each Sensor in the Firestore Database)

The path is occupation.sensor_n.location_id/reserved_by………

admin.firestore().collection("occupation").get().then((sensors:any) => {
  sensors.forEach((sensor:any) =>{
    console.log("after for each=" + sensor.id + sensor.location_id + sensor.reserved_by + sensor.occupied); //collection_id is working

Thanks for your help

>Solution :

The sensor in forEach() is a QueryDocumentSnapshot. It does have id property which seems to be working fine but you need to use data() to access the data in document. Try refactoring the code as shown below:

admin.firestore().collection("occupation").get().then((sensors:any) => {
  sensors.forEach((sensor:any) =>{
    const { location_id, reserved_by, occupied } = sensor.data()
    console.log("after for each = ", sensor.id, location_id, reserved_by, occupied); 
  })
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading