简体   繁体   English

如何在 firestore 中获取单个文档并将其显示在网站上

[英]How to get a single document in firestore and display it on a site

I cant't find a way to get a single document from Cloud Firestore on a website.我找不到从网站上的 Cloud Firestore 获取单个文档的方法。 Let's say I have this Collection on my Cloud Firestore (Not realtime DB):假设我的 Cloud Firestore 上有这个集合(不是实时数据库):

StoreSales:
 StoreA
    Jan:1
    Feb:5
    Mar:10
    Apr:2
    May:3 
 StoreB 
    Jan:1
    Feb:5
    Mar:5
    Apr:6
    May:3
 StoreC
    Jan:1
    Feb:5
    Mar:2
    Apr:2
    May:1

And I have this code to retrieve some data:我有这段代码来检索一些数据:

const Stores = document.querySelector('#sales-list');

function renderSales(doc){
    let li = document.createElement('li');
    let sales = document.createElement('span');

    li.setAttribute('data-id', doc.id);
    sales.textContent = doc.data().StoreSales;

    li.appendChild(sales);

    Stores.appendChild(li);
}

db.collection('StoreSales').get().then(snapshot => {
    snapshot.docs.forEach(doc => {
            console.log(doc.id, ' => ', doc.data());
        renderSales(doc);
    });
});

And what that ends up doing is getting all data, no matter the document and no matter what's inside the sub collections, it will get for example what's on Store A, B and C, and their contents.最终要做的是获取所有数据,无论文档如何,无论子 collections 中有什么,它都会获取例如商店 A、B 和 C 上的内容及其内容。

I wanted to target and display specific data, like for example show the StoreB April sales.我想定位并显示特定数据,例如显示 StoreB 的四月销售额。 What can I modify to get this result?我可以修改什么以获得此结果?

Getting a single document when you know its ID is a straightforward case covered in the documentation .当您知道文档的 ID 时获取单个文档是文档中涵盖的一个简单案例。 I suggest reviewing it.我建议审查它。 You can use doc() to create a reference to that document.您可以使用doc()创建对该文档的引用。

db.collection('StoreSales').doc('StoreA').get().then(snapshot => {
    // Do what you want with the DocumentSnapshot here
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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