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

I hope somebody can help me, I am searching for hours. The problem in this code is that in the log file of Firebase there only stands:

"after for each =undefinedsensor_location_1undefinedundefinedundefined "

so why does it only use the first document (in this case it is location_id which 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 1:[1]

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); 
  })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj