【问题标题】:Is possible to check if a collection or sub collection exists?是否可以检查集合或子集合是否存在?
【发布时间】:2022-01-04 20:31:15
【问题描述】:

有没有办法检查 nodejs 的 firestore 中是否存在子集合?

目前我正在使用doc.exists 处理文档,但我需要检查文档中是否存在子集合以便写入一些数据。

【问题讨论】:

标签: javascript node.js firebase google-cloud-firestore


【解决方案1】:

是的,有。您可以使用 docs.length 来了解子集合是否存在。

我制作了一个示例来指导您,希望对您有所帮助。

 this.db.collection('users').doc('uid')
  .get().then(
  doc => {
    if (doc.exists) {
      this.db.collection('users').doc('uid').collection('friendsSubcollection').get().
        then(sub => {
          if (sub.docs.length > 0) {
            console.log('subcollection exists');
          }
        });
    }
  });

【讨论】:

  • 这很好,但这实际上不会进行 N 次读取。如果是这种情况,最好限制返回文档的数量 => *.limit(1)。
  • 如果集合不包含任何文档怎么办?并且仍然存在?
  • @AkashGorai 没有。没有空集合。
【解决方案2】:

Mateus 的回答对我没有帮助。可能随着时间的推移它已经改变了。

.collection(..).get() 返回一个QuerySnapshot,它具有size 属性,所以我就这样做了:

admin.firestore
     .collection('users')
     .doc('uid')
     .collection('sub-collection')
     .limit(1)
     .get()
     .then(query => query.size);

【讨论】:

  • 有必要使用.limit(1)吗?
  • @EdisonPebojot 不,不是,但是如果您以后不需要获取所有文档,这会限制查询大小 - 可能有利于分页。所以你可以像这样使用它: const snapshot = await admin.firestore.collection(users/${uid}/sub-collection).get() const doesDocsExist = snapshot.size ?真:假
  • 是的。它会更快,并且对您的配额的计数会更少
【解决方案3】:

更准确地说:

const querySnapshot = admin.firestore().collection('users').doc('uid').collection('sub-collection').limit(1).get()
if (querySnapshot.empty) {console.log('sub-collection not existed')}

【讨论】:

    【解决方案4】:

    这就是我能够检查集合是否存在的方法?

    我先定位文档路径,如果存在,则说明集合存在,之后可以访问。

    >  db.collection("collection_name").document("doc_name").get()
    >        .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    >                     @Override
    >                     public void onComplete(@NonNull Task<DocumentSnapshot> task) {
    >                         if(task.isSuccessful()){
    >                             DocumentSnapshot result = task.getResult();
    >                             if(result.exists()){
    >                                *//this means the document exist first, hence the 
    >                                 //collection afterwards the doc_name will 
    >                                 //exist...now I can access the collection*  
    > db.collection("collection_name").document("doc_name").collection("collection_name2").get()
    > .addOnCompleteListener(task1 -> {    if(task1.isSuccessful()){
    >       ...
    >     } }); } } });
    

    【讨论】:

      【解决方案5】:

      这是 NextJS (React) 代码,用于检查集合“users”中是否存在子集合“history” > doc>user-Id, 如果存在,则在历史记录中获取数据,否则保留历史记录 == false。 然后,您可以使用{havehistory?&lt;&gt;&lt;/&gt;:&lt;&gt;&lt;/&gt;} 根据数据显示不同的信息。

          const [history, setHistory] = useState([])
      const [havehistory, setHavehistory] = useState(false)
      
      if(user){
        onSnapshot(query(collection(db, "users", user.uid,"history")), (querySnapshot) => {
          if(querySnapshot){
            const historyBro = querySnapshot.docs.map((doc) => {
              return { ...doc.data(), id: doc.id };
            });
            setHistory(historyBro)
            setHavehistory(true)
          }
        })
      }
      

      确保您导入了所需的模块。例如

      import { useState } from "react";

      import {db} from '../firebase'

      import { collection,doc, query, onSnapshot} from "firebase/firestore";

      import Link from "next/link";

      【讨论】:

        猜你喜欢
        • 2019-01-08
        • 2018-08-11
        • 1970-01-01
        • 2019-12-11
        • 2012-03-10
        • 2012-11-06
        • 1970-01-01
        • 2013-04-20
        相关资源
        最近更新 更多