【问题标题】:Firestore/Javascript: How to get a data from map field of a sub-document?Firestore/Javascript:如何从子文档的地图字段中获取数据?
【发布时间】:2020-02-02 21:59:20
【问题描述】:

我想从我在 firestore 中的子文档的地图中获取特定数据,并将其显示在我的 Web 应用程序页面中。我真的不知道如何在var.textContent = doc.data(). 部分调用数据...

注意:stages 是一张字段图

帮助解决我的问题的图片:

到目前为止,这是我所拥有的:

<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>

编辑

为了进一步澄清我的问题,是否可以使用doc.data() 在 Firestore 中获取字段地图的内容?因为我一直使用doc.data() 来获取子文档的字段。

示例

因为我一直使用doc.data() 来获取子文档的字段。

我设置非地图字段的代码:

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

注意:minutesAsleep 已经是子文档中的非映射字段,可以使用上述代码轻松地从数据库中提取出来。

数据库中的字段minutesAsleep

示例的预期输出:

【问题讨论】:

  • 如果您生成一个最小的可重现示例,这将有很大帮助。
  • @aviya.developer 编辑了新示例和图像,以说明可以轻松地将非地图字段从数据库中提取出来。

标签: javascript firebase google-cloud-firestore


【解决方案1】:

在试验和修改代码之后:

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

替换为:

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

进一步解释:

doc.data().

获取文档数据

那么,

doc.data().stages

获取地图字段阶段下的文档数据

最后,

doc.data().stages.remSleep;

获取map field stage下的docs数据,并获取该map下remSleep的数据。

我希望这可以帮助任何人,尤其是那些使用 javascript 和 firebase 进行开发的人:)

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2020-12-14
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多