简体   繁体   中英

Trouble with accessing Firebase Cloud Firestore

I am using Cloud Firestore and am having some problems accessing a value in a simple database.

Here is how the database is structured

This is the code I am using to access the "basementER-status" field in the database.

//current status value is pulled from database
  function getRawStatus ()
  {
    return db.collection("rooms").doc("roomsDoc").get().then(function(doc) {
      console.log(doc.data()); 
      console.log(doc.data().basementER-status);
      return doc.data().basementER-status;
    });
  }

For the first console.log, this is printed to the console:

{1ER-status: 0, 2ER-status: 0, basementER-status: 0}
1ER-status: 0
2ER-status: 0
basementER-status: 0
__proto__: Object

This is the correct doc that needs to be brought from the database, so I know that part of my code is right.

However, the second console.log prints NaN to the console.

What is happening here? I don't understand. I've accessed fields like this before in cloud firestore and it has always worked.

For your second console.log statement, you are trying to access a specific parameter in an object, so you should use this:

     console.log(doc.data()["basementER-status"]);

For more info, go here: firestore adding data link

The problem is because of the way JavaScript parses your statement. This line:

console.log(doc.data().basementER-status);

Is actually performing a mathematical subtraction between doc.data().basementER and the value of the variable status . That's not what you want.

If you want the value of a field with JavaScript operators or other special characters in it, you will have to use a different syntax:

const data = doc.data();
console.log(data['basementER-status']);

The square brackets let you provide an arbitrary string to look up the name property in the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM