Home > Blockchain >  Cloud Firestore Data Structure making effectively
Cloud Firestore Data Structure making effectively

Time:12-20

I'm thinking of RecyclerView.

For example, users can view posts by region. So I thought of calling the post object differently depending on the region like post1,post2,post3, ... <- collection. A different post object is called for each region set by the user.

I wonder if it's okay to think like this.

CodePudding user response:

It makes sense to create a collection that looks like this:

Firestore-root
  |
  --- posts (collection)
       |
       --- $postId
       |     |
       |     --- region: "USA"
       |     |
       |     --- title: "Post one title"
       |
       --- $postId
             |
             --- region: "Europe"
             |
             --- title: "Post teo title"

And if you want to filter the posts by a specific region, then you should simply perform a query that looks like this:

FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference postsRef = db.collection("posts");
Query queryByRegion = postsRef.whereEqualTo("region", "Europe");
queryByRegion.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    String title = document.getString("title");
                    Log.d(TAG, title);
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage());
        }
    }
});
  • Related