【问题标题】:How to perform a query in Firebase's Cloud Firestore如何在 Firebase Cloud Firestore 中执行查询
【发布时间】:2018-03-20 11:46:51
【问题描述】:

我按照文档here 了解如何编写查询,但我没有从中获得任何数据。数据库已经填充了文档提供的示例

下面是我的代码

var db = firebase.firestore();

var citiesRef = db.collection("cities");
var query = citiesRef.where("state", "==", "CA");

query.get().then(function(doc) {
if (doc.exists) {
    console.log("Document data:", doc.data());
} else {
    console.log("No such document!");
}
}).catch(function(error) {
    console.log("Error getting document:", error);
});

如果我没有对其进行任何查询,它就可以正常工作。例如(也来自文档):

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

【问题讨论】:

    标签: firebase nosql google-cloud-firestore


    【解决方案1】:

    您的两个请求的不同之处在于,在第二种情况下,您正在检索一个文档,该文档为您提供 DocumentSnapshot,该文档具有 exists 属性和 data() 方法。

    在你不工作的例子中,你做了一个查询,它给你一个QuerySnapshot,它的处理方式必须与DocumentSnapshot不同。您获得的不是单个文档,而是文档列表/集合。您可以使用emptysize 属性检查是否已检索到数据,然后使用forEach 方法或docs 数组查看结果:

    var db = firebase.firestore();
    
    var citiesRef = db.collection("cities");
    var query = citiesRef.where("state", "==", "CA");
    
    query.get().then(function(results) {
      if(results.empty) {
        console.log("No documents found!");   
      } else {
        // go through all results
        results.forEach(function (doc) {
          console.log("Document data:", doc.data());
        });
    
        // or if you only want the first result you can also do something like this:
        console.log("Document data:", results.docs[0].data());
      }
    }).catch(function(error) {
        console.log("Error getting documents:", error);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2020-05-06
      • 2021-11-12
      • 2020-08-23
      • 2021-06-19
      • 2018-05-05
      • 2021-04-28
      相关资源
      最近更新 更多