25

I'm currently working on an app where I have to retrieve data from Google's Firestore.

My data structure looks like this:

users
 - name@xxx.com
    - more data

Is there a way for me to change the name@xxx.com to just name? I can't see a method to change the name of a document.

samm82
  • 240
  • 4
  • 14
Mathias Schrooten
  • 722
  • 2
  • 11
  • 20
  • 3
    There is no option to rename/move a document in Cloud Firestore. You will have to copy the data to the new document and then remove the original document. See https://stackoverflow.com/questions/47244403/how-to-move-a-document-in-cloud-firestore – Frank van Puffelen Dec 19 '17 at 14:30
  • Possible duplicate of [How to move a document in Cloud Firestore?](https://stackoverflow.com/questions/47244403/how-to-move-a-document-in-cloud-firestore) – Frank van Puffelen Dec 19 '17 at 14:30

2 Answers2

38

I think the best way to do this is to get the data from 'name@xxx.com' and upload it to a new document called 'name' and then delete the old one.

Just as an example:

const firestore = firebase.firestore();
// get the data from 'name@xxx.com'
firestore.collection("users").doc("name@xxx.com").get().then(function (doc) {
    if (doc && doc.exists) {
        var data = doc.data();
        // saves the data to 'name'
        firestore.collection("users").doc("name").set(data).then({
            // deletes the old document
            firestore.collection("users").doc("name@xxx.com").delete();
        });
    }
});
Bjørn Reemer
  • 490
  • 6
  • 8
0

There might be a case when u realize that you should have used autogenerated IDs for all your firebase documents in a collection and now you want to change the document IDs in your Collection ("collection_name") and also want to store their previous IDs as a new field ("prevID") in the new document then here's what you can do:-

    FirebaseFirestore firebaseDb;
    ArrayList<Map<String,Object>> data = new ArrayList<>();
    firebaseDB.collection("collection_name").get.addOnSuccessListener(
        queryDocumentSnapshots -> {
        for (DocumentSnapshot d : queryDocumentSnapshots) {
            Map<String,Object> map = d.getData();
            map.put("prevID", d.getId());
            data.add(map);
        }
        for(Map<String, Object> d : data){
            Task<DocumentReference> dd = firebaseDb.collection("collection_name").add(d);
                    dd.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            firebaseDb.collection("collection_name").document((String) d.get("prevID")).delete();
                        }
                    });
        }
    });

Frank nike
  • 330
  • 5
  • 12
Saurav Rao
  • 404
  • 5
  • 7