简体   繁体   English

如何在Firestore中检查集合是否包含某些子集合

[英]how to check if a collection contains certain sub collection or not in firestore

在此处输入图片说明

i want to make this type of collection in my firestore 我想在我的firestore进行这种收藏

where chatRooms will be my collection name, combination of myUid and opponentsUid will be my sub-collection in which different documents will be placed. 其中chatRooms将是我的集合名称, myUid and opponentsUid组合将是我的子集合,其中将放置不同的文档。 My problem is i want to check if my collection contains sub-collection named myUid_opponentsUid or opponentsUid_myUid and i am not able to search a best query for doing this. 我的问题是我想检查我的集合是否包含名为myUid_opponentsUidopponentsUid_myUid myUid_opponentsUid ,并且我无法为此搜索最佳查询。

All i know is that we can fetch the whole list and then check if it contains the specific room or not, but its a lengthy process, so i want to better method for it. 我所知道的是,我们可以获取整个列表,然后检查它是否包含特定的房间,但是这是一个漫长的过程,因此,我想为其提供更好的方法。

Thanks in advance. 提前致谢。

There are a few misconceptions in your question to clear up first: 您的问题中有一些误解需要首先解决:

  1. In Firestore collections don't really exist as distinct entities. 在Firestore中,集合并不真正作为不同的实体存在。 It's the documents inside a collection that cause it to become visible. 导致集合可见的是集合中的文档。

  2. Also, collections can only contain documents, which in turn can contain collections, but the structure must alternate, so you can't have a collection called chatRooms that contains a collection myUid_opponentUid. 另外,集合只能包含文档,而文件又可以包含集合,但是结构必须交替,因此您不能有一个名为chatRooms的集合,其中包含一个集合myUid_opponentUid。 Inside chatRooms there must be a document. 在chatRooms内部必须有一个文档。

So if chat rooms contain messages, a straightforward way to do what you want is to create a document that represents that chatRoom. 因此,如果聊天室包含消息,则执行所需操作的直接方法是创建一个代表该chatRoom的文档。 Then within that create a subcollection for the messages. 然后在其中创建消息的子集合。

If you sort the UIDs before creating the composite chatRoom key you can then test whether or not the chat room exists by using a single get() . 如果在创建复合chatRoom键之前对UID进行了排序,则可以使用单个get()测试聊天室是否存在。 The structure would look like this: 结构如下所示:

chatRooms/(uid-pair)/messages/(message-id)

Note that you don't actually need to store anything at the chatRoom/(uid-pair) level to create children at the messages level: you can just create new messages and listen directly. 请注意,您实际上不需要在chatRoom/(uid-pair)级别存储任何内容即可在messages级别创建子级:您只需创建新消息并直接收听即可。

Try to Read Total Number of child .! 尝试读取孩子的总数。 Hope this thing may helps you.and if you want to implement your own api then try using Firebase Functions ..and last thing I want to add is that if You want to add get Count without reading number of child you have to implement one method that getChildCount before storing data and then append them with key like JiGh_31GA20JabpZBfa ,1` and only read keys and then use comma separator and you will get your result that this parent contains child or not.? 希望这件事对您有帮助。如果您想实现自己的api,请尝试使用Firebase Functions ..最后我要补充的是,如果要添加get Count而不读取子代数,则必须实现一个方法该getChildCount在存储数据之前,然后将其附加诸如JiGh_31GA20JabpZBfa ,1`之类的JiGh_31GA20JabpZBfa ,并且仅读取密钥,然后使用逗号分隔符,您将得到该父项是否包含子项的结果。

    DatabaseReference myRef = database.getReference();

      //You can use the single or the value.. depending if you want to keep track
     String id= UUID.randomUUID().toString();//randomID for task

    Object object=new Object ();      




    public int chidcount(String child){

 string childcount="0";


  //You can use the single or the value.. depending if you want to keep track
 myRef.child(child).addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
   for (DataSnapshot snap: dataSnapshot.getChildren()) {

        childcount=snap.getChildrenCount();
        Log.e(snap.getKey(),snap.getChildrenCount() + "");
    }

    addvalue(childcount);

   }

  @Override
 public void onCancelled(DatabaseError databaseError) {

    }
        });

}


private addvalue(String childcount){
 object=setid(id);

     object=setname("name");

      getchildCount("object");

        mdatabaseRef.child("rating").child(manager.getId()+childcount).child(currentEmployee.getId()).child(id).setValue(rating);}

I know I am late. 我知道我迟到了。 Posting for future users. 为将来的用户发布。 Try this: 尝试这个:

DocumentReference datab = db.collection("collection_name").document("Doc_name");


                    datab.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                        @Override
                        public void onSuccess(DocumentSnapshot documentSnapshot) {

                            if(documentSnapshot.contains("field_name"))
                            {
                                Toast.makeText(YourActivity.this, "Child exixts.", Toast.LENGTH_SHORT).show();

                            }
                            else
                                Toast.makeText(YourActivity.this, "Doesnt exits.", Toast.LENGTH_SHORT).show();


                        }
                    });

For Firebase Firestore to check whether the document has entries (fields), Use this command 为了使Firebase Firestore检查文档是否具有条目(字段),请使用此命令

firebaseFirestore.collection("Users").document(userId)
  .addSnapshotListener {
    documentSnapshot, _ ->
        if (documentSnapshot!!.contains("name")) {
            Log.i("Name", "Name exists")
        } else {
            Log.i("Name", "Name doesn't exists")
        }
}

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

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