React Native和Firebase:无法从数据库检索文档

时间:2020-04-10 14:20:08

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

我正在尝试做世界上最简单的事情:从我的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.

我的Internet连接很好。

我的问题

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

似乎我滥用语法或缺少库(尽管我使用的库允许我updateset使用,所以我假设get设置文档也应该在同一个库中。任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

Firebase包含两个数据库:

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

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

如果您正在使用实时数据库,则可以通过const cheerio = require('cherio'); const $ = cheerio.load(content); // content is your HTML scraped result = $('. productDetailsLink').text(); 从JavaScript中访问它,并使用firebase.database()从该数据库中的某个位置访问它。

如果您正在使用Cloud Firestore,则可以使用ref("...").child("...")从JavaScript中访问它,并使用firebase.firestore()从文档中访问它。

您的代码正在混合使用这些API,这将无法正常工作。要访问文档,您需要以下内容:

collection("...").doc("...")

将会摆脱firebase.firestore().collection("users") .where("geohash", ">=", lower) .where("geohash", "<=", upper) .get() .then((docs) => console.log(docs)); 消息。

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