How to move a document in Cloud Firestore?

Can someone help me how to rename, move or update document or collection names in Cloud Firestore?

Also is there anyway that I can access my Cloud Firestore to update my collections or documents from terminal or any application?


Solution 1:

Actually there is no move method that allows you to simply move a document from a location to another. You need to create one. For moving a document from a location to another, I suggest you use the following method:

public void moveFirestoreDocument(DocumentReference fromPath, final DocumentReference toPath) {
    fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document != null) {
                    toPath.set(document.getData())
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d(TAG, "DocumentSnapshot successfully written!");
                                fromPath.delete()
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            Log.d(TAG, "DocumentSnapshot successfully deleted!");
                                        }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Log.w(TAG, "Error deleting document", e);
                                        }
                                });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w(TAG, "Error writing document", e);
                            }
                        });
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });
}

In which fromPath is the location of the document that you want to be moved and toPath is the location in which you want to move the document.

The flow is as follows:

  1. Get the document from fromPath location.
  2. Write the document to toPath location.
  3. Delete the document from fromPath location.

That's it!

Solution 2:

Here's another variation for getting a collection under a new name, it includes:

  1. Ability to retain original ID values
  2. Option to update field names

    $(document).ready(function () {

        FirestoreAdmin.copyCollection(
            'blog_posts',
            'posts'
        );

    });

=====

var FirestoreAdmin = {

    // to copy changes back into original collection
    // 1. comment out these fields
    // 2. make the same call but flip the fromName and toName 
    previousFieldName: 'color',
    newFieldName: 'theme_id',

    copyCollection: function (fromName, toName) {

        FirestoreAdmin.getFromData(
            fromName,
            function (querySnapshot, error) {

                if (ObjectUtil.isDefined(error)) {

                    var toastMsg = 'Unexpected error while loading list: ' + StringUtil.toStr(error);
                    Toaster.top(toastMsg);
                    return;
                }

                var db = firebase.firestore();

                querySnapshot.forEach(function (doc) {

                    var docId = doc.id;
                    Logr.debug('docId: ' + docId);

                    var data = doc.data();
                    if (FirestoreAdmin.newFieldName != null) {

                        data[FirestoreAdmin.newFieldName] = data[FirestoreAdmin.previousFieldName];
                        delete data[FirestoreAdmin.previousFieldName];
                    }

                    Logr.debug('data: ' + StringUtil.toStr(data));

                    FirestoreAdmin.writeToData(toName, docId, data)
                });
            }
        );
    },

    getFromData: function (fromName, onFromDataReadyFunc) {

        var db = firebase.firestore();

        var fromRef = db.collection(fromName);
        fromRef
            .get()
            .then(function (querySnapshot) {

                onFromDataReadyFunc(querySnapshot);
            })
            .catch(function (error) {

                onFromDataReadyFunc(null, error);
                console.log('Error getting documents: ', error);
            });
    },

    writeToData: function (toName, docId, data) {

        var db = firebase.firestore();
        var toRef = db.collection(toName);

        toRef
            .doc(docId)
            .set(data)
            .then(function () {
                console.log('Document set success');
            })
            .catch(function (error) {
                console.error('Error adding document: ', error);
            });

    }

}

=====

Here's the previous answer where the items are added under new IDs

        toRef
            .add(doc.data())
            .then(function (docRef) {
                console.log('Document written with ID: ', docRef.id);
            })
            .catch(function (error) {
                console.error('Error adding document: ', error);
            });