Firestore - How to get document id after adding a document to a collection

后端 未结 6 1608

Is there a way to acquire the document id that was generated after adding a document to a collection?

If I add a document to a collection that represents a \"post\"

6条回答
  •  有刺的猬
    2020-12-08 04:43

    For Android, Java, you're suppose to get the Document ID before you set() or add() something to Firestore. Like so:

    //Fields: 
    CollectionReference toolsCollectionRef = FirebaseFirestore.getInstance().collection(toolsCollection);
    CustomPOJO_Model toolToPost; 
    
    //In Methods: 
    String newDocID= toolsCollectionRef.document().getId();   //Get Doc ID first. 
    toolToPost.setToolID(newDocID);
    
    //Now use the doc ID:
    toolsCollectionRef.document(newDocID).set(toolToPost.getConvertedTool_KeyValuePair ()).addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
        }
    });
    
    //Re-use same ID in another post: 
    usersCollectionRef.document(mAuth.getUid()).collection(usersToolsCollection).document(toolToPost.getToolID()).set(toolToPost.getConvertedTool_KeyValuePair()); 
    

提交回复
热议问题