如何在 Cloud Firestore 中移动文档?

How to move a document in Cloud Firestore?

有人可以帮助我如何在 Cloud Firestore 中重命名、移动或更新文档或 collection 名称吗?

另外,我是否可以访问我的 Cloud Firestore 以更新我的 collection 或来自终端或任何应用程序的文档?

实际上没有 move 方法可以让您简单地将文档从一个位置移动到另一个位置。你需要创建一个。要将文档从一个位置移动到另一个位置,我建议您使用以下方法:

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());
            }
        }
    });
}

其中 fromPath 是您要移动的文档位置,toPath 是您要移动文档的位置。

流程如下:

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

就是这样!

这是使用新名称获取集合的另一种变体,它包括:

  1. 能够保留原始 ID 值
  2. 更新字段名称的选项

    $(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);
            });

    }

}

=====

这是以前的答案,其中项目已添加到新 ID 下

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

我在 Swift 中解决了这个问题。您从文档中检索信息,将其放入新位置的新文档中,删除旧文档。 代码如下所示:

    let sourceColRef = self.db.collection("/Users/users/Collection/")
    colRef.document("oldDocument").addSnapshotListener { (documentSnapshot, error) in
                if let error = error {
                            print(error)
                        } else {
                            DispatchQueue.main.async {
                            if let document = documentSnapshot?.data() {
                                
                                let field1 = document["Field 1"] as? String // or Int, or whatever you have)
                                let field2 = document["Field 2"] as? String
                                let field3 = document["Field 3"] as? String
                                
                                
                  let newDocRef = db.document("/Users/users/NewCollection/newDocument")
                                newDocRef.setData([
                                        "Field 1" : field1!,
                                        "Field 1" : field2!,
                                        "Field 1" : field3!,
                                        
                                ])
                            }
                          }
                        }
                    }
            
            sourceColRef.document("oldDocument").delete()