How could I set sub-collect in firestore?
this is my real-time DB format
I tried to use this way db.collection("Report").document("Post").set(hashMap).addOnSuccessListener
but it cannot set my post id (-MkllN0v3il1s85g4BT4)
-MkllN0v3il1s85g4BT4 is my post id.
Then I use DocumentReference d1 = db.document("Report/Post");
But how can set document(postid) ?
real-time DB hashMap way
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Report").child("Post");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("publisher",FirebaseAuth.getInstance().getCurrentUser().getUid());
hashMap.put("time", ServerValue.TIMESTAMP);
hashMap.put("info", edt_comment.getText().toString());
reference.child(postModel.getPostid()).setValue(hashMap);
CodePudding user response:
If you want to be completely free to determine the tree to store, you should stick to the Realtime Database.
If on the other hand you want to switch to Firestore, you'll have to find a way to map your data model (not just the JSON, but the model of your app too) into Firestore's document/collection model.
I find it helpful to use plurals for collection names, so that it is clear even from just the name that these are collections. The document names are typically generated, either by the database itself or by some other system (like UIDs for users, or timestamps for date/time).
With that knowledge in mind, I'd expect your structure to be:
Reports (collection)
$reportID (docs)
Posts (collection)
$postID (docs)
Even if there's only a single report in the application, I'd use this approach. In that case I'd use a fixed name/document ID for that report:
Reports (collection)
Default (doc)
Posts (collection)
$postID (docs)
If you are not looking to ever expand the number of reports, nor store information in the Default
document for the report, you might consider removing the top-level collection altogether, and model it as:
ReportPosts (collection)
$postID (docs)