首页 > 解决方案 > Firestore Uncaught TypeError:doc.data 不是函数

问题描述

当我想在 node.js html 中显示来自 firestore 的数据时,这两个代码出现错误:productName.textContent = doc.data().name; productPrice.textContent = doc.data().price;

浏览器控制台 火库


const myProducts = db.collection('products');
const productsContainer = document.querySelector('#groceries');

 function renderProduct(doc) {
   const docFrag = document.createDocumentFragment();
   let article = document.createElement('article');
   let productName = document.createElement('h4');
   let productPrice = document.createElement('p');

   article.setAttribute('id', doc.id);
   productName.textContent = doc.data().name;
   productPrice.textContent = doc.data().price;

   docFrag.appendChild(productName);
   docFrag.appendChild(productPrice);

   article.appendChild(docFrag);
   productsContainer.appendChild(article);
 }

 myProducts.onSnapshot(products => {
   products.forEach(doc => {
     products = doc.data();
     console.log(products);
     renderProduct(products);
   });
 });

 class shop extends React.Component {

    render() {
        return (
            <div className="app-wrapper">
                <ContainerHeader match={this.props.match} title={<IntlMessages id="appModule.contactSupport"/>}/>
                <div className="d-flex justify-content-center">
                    <div id="groceries"></div>

                </div>
            </div>
        );
    }
}

标签: javascriptnode.jsgoogle-cloud-firestore

解决方案


似乎您正在传递数据,而不是对 的文档引用renderProduct,因此您只需直接访问道具:

function renderProduct(data) {
   // ...
   article.setAttribute('id', data.id);
   productName.textContent = data.name;
   productPrice.textContent = data.price;
   // ...

推荐阅读