问题描述
我正在使用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');
我想处理两种情况
-
没有符合条件的文件
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中,您可以使用 QuerySnapshot
由 get()
方法:
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中使用查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!