【问题标题】:React Native and Firebase: Retrieving documents from a database not workingReact Native 和 Firebase:从数据库中检索文档不起作用
【发布时间】:2020-04-10 14:20:08
【问题描述】:

我正在尝试做世界上最简单的事情:从我的 firebase 数据库中检索文档,但事实证明这是不可能的。我正在使用 React Native 和 Expo。

我正在尝试做这样的事情:

import * as firebase from 'firebase';

// ... React component

useEffect(() => {
  firebase.database().collection("users")
  .where("geohash", ">=", lower)
  .where("geohash", "<=", upper)
  .get()
  .then((docs) => console.log(docs));
}, []);

我目前收到以下错误:

firebase.database().collection is not a function.

到目前为止我已经尝试过什么

This question 说将firebase.database() 更改为firebase.firestore(),但是,这不仅对我不起作用,而且我还在我的应用程序的其他部分使用firebase.database().ref("/users/" + uid).set() 和firebase.database()ref("/users/" + uid).update() 没有问题,所以我不要认为我应该将其更改为firebase.firestore()。当我确实改变它时,它仍然会抛出一个错误:

Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=not-found]: The project test-app8768 does not exist or it does not contain an active Cloud Datastore or Cloud Firestore database. Please visit http://console.cloud.google.com to create a project or https://console.cloud.google.com/datastore/setup?project=test-app8768 to add a Cloud Datastore or Cloud Firestore database. Note that Cloud Datastore or Cloud Firestore always have an associated App Engine app and this app must not be disabled. This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

我的互联网连接非常好。

我的问题

无论如何,我的问题很简单:在使用 Expo 的 React Native App 中,我如何使用 firebase 从数据库中检索文档?

似乎我在滥用语法或缺少一个库(尽管我使用的是允许我使用 update 和 set 的同一个库,所以我假设 getting文档也应该在同一个库中)。非常感谢任何帮助。

【问题讨论】:

    标签: firebase react-native google-cloud-firestore expo


    【解决方案1】:

    Firebase 包含两个数据库:

    • 实时数据库,将数据存储为单个 JSON 树,以及
    • Cloud Firestore,将数据存储在文档和集合中。

    这些数据库的 API 是完全独立的,因此您不能在另一个数据库上使用其中一个的 API。

    如果您使用的是实时数据库,您可以通过 firebase.database() 从 JavaScript 访问它,并使用 ref("...").child("...") 在该数据库中的某个位置进行访问。

    如果您使用 Cloud Firestore,则可以使用 firebase.firestore() 从 JavaScript 访问它,并使用 collection("...").doc("...") 访问文档。

    您的代码混合了这些 API,这是行不通的。要访问文档,您需要这样的东西:

    firebase.firestore().collection("users")
      .where("geohash", ">=", lower)
      .where("geohash", "<=", upper)
      .get()
      .then((docs) => console.log(docs));
    

    哪个将删除firebase.database().collection is not a function.消息。

    我建议您花时间阅读 getting started 上的文档,使用 Firestore,因为它可以防止您在以后遇到许多类似的问题。

    【讨论】:

    • 感谢您的澄清。这是否意味着如果我将数据保存在实时数据库中,并且我想以我在问题中引用的方式访问这些数据,我应该将其同时保存在实时数据库和 Firestore 中?
    • 看来是这样。我将不得不稍微重新排列我的数据结构。感谢您为我指明正确的方向。
    猜你喜欢
    • 2019-03-25
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多