简体   繁体   English

你如何从firestore读取数据?

[英]How do you read data from firestore?

I'm trying to learn how to use firestore.我正在尝试学习如何使用 firestore。

The google documentation says to try this format: 谷歌文档说尝试这种格式:

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

So, I used that to do this (changing the db to fsDB and "users" to "newsletters"所以,我用它来做到这一点(将 db 更改为 fsDB,将“users”更改为“newsletters”

fsDB.collection("newsletters").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

When I try this, I get an error that says querySnapshot is not defined.当我尝试这样做时,我收到一条错误消息,指出未定义 querySnapshot。 Screen shot of error message is attached.附上错误消息的屏幕截图。

在此处输入图片说明

I've seen this post and tried its suggestion as follows:我看过这篇文章并尝试了如下建议:

fsDB.collection("newsletters").query.get().then(function(querySnapshot) { 

                            if (querySnapshot.empty) { 
                                console.log('no documents found');
                            } else {
                                    querySnapshot.docs.map(function (documentSnapshot) {
                                        console.log(documentSnapshot.data().name); 
                                    });
                            }

                        });

This attempt generates a parsing error with the if statement, but I can't find a way to solve that either.此尝试使用 if 语句生成解析错误,但我也找不到解决此问题的方法。

This must have a simple solution, but I can't figure out how to get a record from the database.这必须有一个简单的解决方案,但我不知道如何从数据库中获取记录。

NEXT ATTEMPT下一次尝试

I tried moving the code above the return statement and putting in inside a variable as follows shown in the attached screen shot, but it still produces errors as shown.我尝试将代码移到 return 语句上方并放入一个变量中,如下所示的附加屏幕截图所示,但它仍然产生如图所示的错误。 These errors are the same regardless of whether i keep or lose the brackets around querySnapshot.无论我保留还是丢失 querySnapshot 周围的括号,这些错误都是相同的。

ADD STATE添加状态

class Fndate extends React.Component {
    state = {
        options: [],
        anzic: [],
        country: [],
        region: [],

    }

    selectCountry (val) {
        this.setState({ country: val });
      }

      selectRegion (val) {
        this.setState({ region: val });
      }

    async componentDidMount() {
        // const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
        let options = [];
        await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            options.push({
                value: doc.data().title.replace(/( )/g, ''),
                label: doc.data().title + ' - ABS ' + doc.id
            });
            });
        });


        let anzic = [];
        await fsDB.collection("anzic_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            anzic.push({
                value: doc.data().Title.replace(/( )/g, ''),
                label: doc.data().Title + ' - ANZIC ' + doc.id
            });
            });
        });


            await fsDB
            .collection("newsletter")
            .get().then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                console.log(`${doc.id} => ${doc.data().email}`);
                }
            );
            });

        this.setState({
            options,
            anzic
        });
    }

在此处输入图片说明 5 ] 5 5 ] 5

I believe you're using React, and I just realized that you're calling the method in question in the render method.我相信您正在使用 React,并且我刚刚意识到您正在调用render方法中的相关方法。

try doing it in componentDidMount .尝试在componentDidMount执行此操作。 A reference can be found here可以在这里找到参考

so your code would be like this:所以你的代码会是这样的:

class YourClass extends React.Component {
   componentDidMount(){
      fsDB.collection("newsletters").get().then((querySnapshot) => {
         querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
         });
      });
   }
   render(){
      return (....your existing jsx....)
   }
}

Note that I don't know your class name or how you define your component.请注意,我不知道您的类名或您如何定义组件。 But I'm just saying that you need to move your code in the componentDidMount .但我只是说您需要在componentDidMount移动您的代码。

We couldn't see your entire file.我们无法看到您的整个文件。 But I'm sure that it's a syntax error (especially with JSX)但我确定这是一个语法错误(尤其是 JSX)

I think you should get rid of '.query'.我认为你应该摆脱'.query'。 and the .empty returns false if you have data in the collection.如果集合中有数据,则.empty返回false but i wonder, why is querySnapshot undefined in your case.但我想知道,为什么在您的情况下未定义querySnapshot

db.collection("lessons").get()
  .then(function(querySnapshot) { 
    if (!querySnapshot.empty) {
        querySnapshot.docs.map(function(documentSnapshot) {
        console.log(documentSnapshot.data().name); 
     })
    } else {
    console.log('no documents found');
    }   
});

console安慰

安慰

You can use an automated script for this.您可以为此使用自动化脚本。 All you need is python and firebase_admin.您只需要 python 和 firebase_admin。

  1. pip install firebase_admin pip 安装 firebase_admin
  2. download https://github.com/harshit0209/firestore_backup下载https://github.com/harshit0209/firestore_backup
  3. now run getData.py script.现在运行 getData.py 脚本。
  4. give it the path of your firebase project private key.给它你的 firebase 项目私钥的路径。
  5. now give the document name.现在给出文档名称。

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

相关问题 您如何正确地从 firestore 查询中提取数据并将其用于反应原生组件? - How do you properly extract data from a firestore query and use it in a react native component? 你如何从 Firebase Firestore 中分离一个 onSnapshot 侦听器 - How do you detach an onSnapshot listener from Firebase Firestore 如何在计划 function 中从 Firestore 数据库中读取数据? - How can I read data from firestore database in a schedule function? 您如何使用node.js从mySQL读取数据并将其发布回HTML? - How do you read data from mySQL using node.js and post back to HTML? 如何防止Kendo UI组合框在读取数据时重新填充? - How do you prevent a Kendo UI combobox from refilling on Data Read? 如何将“引用”值插入到 firestore 中? - How do you insert a “reference” value into firestore? 如何在 Firebase Firestore 中创建子集合? - How do you create a subcollection in Firebase Firestore? 如何从 Firestore 集合中的文档中获取数据? - How do I get the data from a document in a collection in Firestore? 如何在反应中从 firestore 获取特定 id 的数据? - How do I get data on a specific id from firestore in react? 如何使用 JavaScript 中的 OR 运算符从 Firestore 检索数据? - How do I retrieve data from Firestore using an OR Operator in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM