[英]How do I check if collection exist in firestore (not document) in JS
Hoi, I would like to check, using React javascript, if a collection in the Firestore already exists, no matter if it's empty or not.嘿,我想使用 React javascript 检查 Firestore 中的集合是否已经存在,无论它是否为空。 I tried:
我试过:
if (collection(db, ref)) // is always true somehow
Any ideas?有任何想法吗? Thanks!
谢谢!
You would need to try to fetch from the collection and see if anything is returned:您需要尝试从集合中获取并查看是否返回任何内容:
const snap = await query(collection(db, ref), limit(1));
if (snap.empty) {
// no docs in collection
}
There is no function available in the SDK that can help you can check if a particular collection exists. SDK 中没有可用的功能可以帮助您检查特定集合是否存在。 A collection will start to exist only if it contains at least one document.
只有至少包含一个文档的集合才会开始存在。 If a collection doesn't contain any documents, then that collection doesn't exist at all.
如果集合不包含任何文档,则该集合根本不存在。 So that being said, it makes sense to check whether a collection contains or not documents.
话虽如此,检查集合是否包含文档是有意义的。 In code, it should look as simple as:
在代码中,它应该看起来很简单:
const snapshot = await query(collection(db, yourRef), limit(1));
if (snapshot.empty) {
//The collection doesn't exist.
}
One thing to mention is that I have used a call to limit(1)
because if the collection contains documents, then we limit the results so we can pay only one document read.值得一提的是,我使用了对
limit(1)
的调用,因为如果集合包含文档,那么我们会限制结果,因此我们只能支付阅读一份文档的费用。 However, if the collection doesn't exist, there is still one document read that has to be paid.但是,如果该集合不存在,则仍然需要支付一份阅读文件。 So if the above query yields no resul## Heading ##t, according to the official documentation regarding Firestore pricing , it said that:
因此,如果上述查询没有产生结果## Heading ##t,根据有关Firestore 定价的官方文档,它表示:
Minimum charge for queries
查询的最低费用
There is a minimum charge of one document read for each query that you perform, even if the query returns no results.
对于您执行的每个查询,即使查询不返回任何结果,也需要读取一个文档的最低费用。
You have to fetch the collection out of the database and check if it has more than 0 documents.您必须从数据库中取出集合并检查它是否有超过 0 个文档。 Even, if the collection doesn't exist, it will return 0.
即使集合不存在,它也会返回 0。
const db = firebase.firestore();
db.collection("YOUR COLLECTION NAME").get().then((res) =>{
if(res.size==0){
//Collection does not exist
}else{
//Collection does exist
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.