Home > Software engineering >  Firebase: Why does my Code only use the first document in my Collection?
Firebase: Why does my Code only use the first document in my Collection?

Time:04-07

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

CodePudding user response:

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