首页 > 解决方案 > Firestore Java Android Create a structure with collections and nested documents

问题描述

I am creating a post system on an android application I am using Firebase. The posts I have decided that I want to put them on the firestore because it is made to contain large amounts of data. So, I want to use this data structure:

--- posts (collection)
         |
         --- uid (documents)
              |           
              |
              ---- postId (documents)
                          |
                          --- title: "Post Title"
                          |
                          --- date: September 03, 2018 at 6:16:58 PM UTC+3
                          |
                          --- valutation: 8
                          [...] etc
                    

I currently know how to add only one collection with the corresponding data schema, like so:

    Map<String, Object> post = new HashMap<>();
    post.put("title", title);
    post.put("description", description);
    post.put("valutation", valutation);
    post.put("genre", filmGenre);
    post.put("urlImage", urlImage);
    post.put("date", dateSeq.toString());

    dbRef.collection("posts").add(post); 

But this would look like this on the firestore:

 --- posts (collection)
             |
             |
             --- title: "Post Title"
             |
             --- date: September 03, 2018 at 6:16:58 PM UTC+3
             |
             --- valutation: 8
             [...] etc

So I would like to create with java the structure that I showed at the beginning of the post, could someone help me?

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


Collection or sub collection can have document.A document can't hold another document directly.so use below method to place document under "postId" sub collection.

Map<String, Object> post = new HashMap<>();
    post.put("title", title);
    post.put("description", description);
    post.put("valutation", valutation);
    post.put("genre", filmGenre);
    post.put("urlImage", urlImage);
    post.put("date", dateSeq.toString());

   //you only need to pass uid and postId

    dbRef.collection("posts").document(uid)
        .collection(postId).add(post); 

推荐阅读