[英]how to check if my cloud firestore collection contains contains any documents
[英]how to check if a collection contains certain sub collection or not in firestore
您的问题中有一些误解需要首先解决:
在Firestore中,集合并不真正作为不同的实体存在。 导致集合可见的是集合中的文档。
另外,集合只能包含文档,而文件又可以包含集合,但是结构必须交替,因此您不能有一个名为chatRooms的集合,其中包含一个集合myUid_opponentUid。 在chatRooms内部必须有一个文档。
因此,如果聊天室包含消息,则执行所需操作的直接方法是创建一个代表该chatRoom的文档。 然后在其中创建消息的子集合。
如果在创建复合chatRoom键之前对UID进行了排序,则可以使用单个get()
测试聊天室是否存在。 结构如下所示:
chatRooms/(uid-pair)/messages/(message-id)
请注意,您实际上不需要在chatRoom/(uid-pair)
级别存储任何内容即可在messages
级别创建子级:您只需创建新消息并直接收听即可。
尝试读取孩子的总数。 希望这件事对您有帮助。如果您想实现自己的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);}
我知道我迟到了。 为将来的用户发布。 尝试这个:
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();
}
});
为了使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.