【问题标题】:How to retrieve first and last collection from Firestore如何从 Firestore 中检索第一个和最后一个集合
【发布时间】:2020-02-11 20:27:08
【问题描述】:

我正在尝试从 Firebase 检索数据并将其添加到 div 的 innerHTML 中,但我只得到最后一个集合(矩阵)但是,当我执行 console.log 时,我得到了所有集合。有人可以帮忙吗?

script: 

const db = firebase.firestore();
const movies = db.collection("movies");

movies.add({
 title: "Jurassic Park",
 Director: "Steven Spielberg"

movies.add({
 title: "The Matrix",
 Director: "The W. brothers"

const container = document.getElementById("container");

movies.onSnashot( snap => {
 for(const movie of snap.docs) {
 const id = movie.id;
 const data = movie.data();

 Console.log(movie.title);
 container.innerHTML = movie.title + " is a great movie"

HTML: 

<div id="container"></div>

【问题讨论】:

    标签: javascript html google-cloud-firestore


    【解决方案1】:

    您的代码只是在每次循环中覆盖相同的容器 innerHTML。听起来您希望它每次都会添加新的文本或元素。

    如果要添加新文本,请尝试追加到 container.innerHTML 而不是每次都覆盖它:

    container.innerHTML += movie.title + " is a great movie"
    

    注意 += 而不是 =。这可能也不会像您期望的那样呈现,但您至少应该看到所有电影标题都挤在一个元素中。

    由于您使用的数据库侦听器会在每次集合中的某些内容发生更改时被调用,因此您还应该考虑清除该容器中的内容,而不是每次都盲目地追加:

    movies.onSnashot( snap => {
      container.innerHTML = ""
      for(const movie of snap.docs) {
        const id = movie.id;
        const data = movie.data();
        container.innerHTML += movie.title + " is a great movie"
      }
    })
    

    【讨论】:

    • 我会使用 textContent 而不是 innerHTML 来减少 XSS 的机会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2023-03-05
    • 2018-05-06
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多