简体   繁体   中英

Firestore/Javascript: How to get a data from map field of a sub-document?

I want to get a specific data from a map of my sub-document in firestore and display it my web application page. I don't really know how to call the data during the var.textContent = doc.data(). part...

Note: stages is a field map

Image to help with my question:

在此处输入图片说明

So far this is what I have:

<script>
firebase.auth().onAuthStateChanged(user => {
 if(user){
  this.userId = user.uid;
 } //stores the user id in variable

const fitbitremSleep= document.querySelector('#fitbitSleepListRemSleep');

function renderFitbitSleep(doc){

 let li = document.createElement('li');
 li.setAttribute('data-id', doc.id);

 let remSleep = document.createElement('span');
 let lbremSleep = document.createElement('span');

 remSleep.textContent = doc.data();
 lbremSleep.textContent = "Minutes of REMSleep:  ";  

 li.appendChild(lbremSleep);
 li.appendChild(remSleep);

 fitbitremSleep.appendChild(li);
 }

 let userRef1 = 
 firebase.firestore().collection("users").doc(userId).collection("fitbit_sleep").orderBy("dateAdded", 
 "desc").limit(1);
 return userRef1.get()
 .then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
   console.log(doc.id, " => ", doc.data());
   renderFitbitSleep(doc);
   });
  })
  .catch(function(error) {
   console.log("Error getting documents: ", error);
    });
   });
});
</script>

EDIT

To clarify my question even more is it possible to get a content of field map in firestore using doc.data() ? Because I've been using doc.data() to get fields of a sub-document.

EXAMPLE

Because I've been using doc.data() to get fields of a sub-document.

My code to set a non-map field:

minutesAsleep.textContent = doc.data().minutesAsleep;

note that: minutesAsleep is non-map field within the sub-document already and can be easily pulled out from the database using the aforementioned code.

Field minutesAsleep in the database: 在此处输入图片说明

EXPECTED OUTPUT OF THE EXAMPLE: 在此处输入图片说明

After experimenting and tinkering with the code:

 remSleep.textContent = doc.data();
 lbremSleep.textContent = "Minutes of REMSleep:  ";

Replace with this:

 remSleep.textContent = doc.data().stages.remSleep;
 lbremSleep.textContent = "Minutes of REMSleep:  ";

to explain further:

doc.data().

gets the docs data

then,

doc.data().stages

gets the docs data under map field stages

finally,

doc.data().stages.remSleep;

gets the docs data under map field stages and gets the data of remSleep under that map.

I hope this could help anyone especially those who are developing using javascript and firebase :)

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