如何在Firebase Firestore中使用查询 [英] How to use Query in Firebase Firestore

查看:103
本文介绍了如何在Firebase Firestore中使用查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase函数和Firebase Firestore开发用于存储用户数据的API.

I am using Firebase function and Firebase Firestore to develope an API which will store users data.

我想使用存储在文档字段中的属性来查找文档. 是Firebase文档,其中说明了如何实现相同的目标./p>

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.

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

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

我想处理两种情况

  1. 没有符合条件的文件

  1. Where there is no document with the present conditions

具有两个以上具有当前条件的文档

Where there are more than two documents with the present conditions

如何处理以上两种情况?

How could the above two situation be handled?

推荐答案

在上面的注释中,按照我们的讨论",在Cloud Function中,您可以使用

Following our "discussion" in the comments above, in a Cloud Function you could do as follows, using the QuerySnapshot returned by the get() method:

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");
        } 
    });

如上所述,请注意,这将花费阅读集合中每个文档的成本.如果您有一个非常大的集合,则可以编写一个Cloud Function,该函数每次在该集合中添加文档或从中删除文档时都会更新计数器.

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.

这篇关于如何在Firebase Firestore中使用查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆