简体   繁体   English

如何在 Firebase Firestore 中使用查询

[英]How to use Query in Firebase Firestore

I am using Firebase function and Firebase Firestore to develope an API which will store users data.我正在使用 Firebase 函数和 Firebase Firestore 来开发一个用于存储用户数据的 API。

I wanted to locate the documents using the properties stored in their field.我想使用存储在其字段中的属性来定位文档。 This is the Firebase document which states how to achieve the same. 是 Firebase 文档,其中说明了如何实现相同的目标。

// Create a reference to the cities collection
var citiesRef = db.collection('cities');

// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');

I wanted to handle two situations我想处理两种情况

  1. Where there is no document with the present conditions如果没有符合当前条件的文件

  2. Where there are more than two documents with the present conditions如果有两个以上的文件符合当前条件

How could the above two situation be handled?以上两种情况如何处理?

Following our "discussion" in the comments above, in a Cloud Function you could do as follows, using the QuerySnapshot returned by the get() method:按照上面评论中的“讨论”,在 Cloud Function 中,您可以使用get()方法返回的QuerySnapshot执行以下操作:

admin.firestore().collection("cities")
    .where('state', '==', 'CA')
    .get()
    .then(querySnapshot => {
        if (querySnapshot.size == 0) {
            console.log("0 documents");
        } else if (querySnapshot.size > 2) {
            console.log("More than 2 documents");
        } 
    });

As said, above, just be aware that this will cost a read for each document in the collection.如上所述,请注意,这将花费读取集合中的每个文档。 In case you have a very large collection, you could write a Cloud Function that update a counter each time a doc is added/removed to/from the collection.如果您有一个非常大的集合,您可以编写一个云函数,每次在集合中添加/删除文档时都会更新计数器。

The accepted answer does not show how to extract the data from each document and imo is only half the answer.接受的答案没有显示如何从每个文档中提取数据,而 imo 只是答案的一半。 the following will get you iterating through every document and extracting the data.以下内容将使您遍历每个文档并提取数据。

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM