简体   繁体   中英

firestore get field from all documents in collection

I'm trying to setup a chat app in which you can search for random users to talk to. Right now, my database structure in firestore is the following:

collection "users" - document "userID" - collection "conversations" - document "conversationID" - fields "partner" , "lastmessage"

Next to that I have a collection "conversations" which contains all the messages in the conversation.

What I'm trying to do now is that when you press a button, the application will search for a random user to chat with but ofcourse I don't want to suggest the same person twice. So I want to find out with which other user he/she already has a conversation with. I believe I can find it with the "partner" field but I can't find how to get all partners for the specific user.

Can you help me setting up the correct firestore "query" to get this information? Or would it be better practice to generate an other link (but then I have duplicate data), for example: collection "users" - document "userID" - collection "partners" - documents with the partnerID

All I had to do was creation a reference to my collection, query it and loop over all my documents. (based on this answer: https://stackoverflow.com/a/55919881/3417559 )

CollectionReference colRef = db.collection("users").document(mFirebaseAuth.getUid()).collection("conversations");
colRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
   @Override
   public void onComplete(@NonNull Task<QuerySnapshot> task) {
      if (task.isSuccessful()) {
          for (QueryDocumentSnapshot document : task.getResult()) {
              Log.d("FABTAG","partnerID" + document.getString("partner"));
          }
      }
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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