Firestore - 创建集合的副本 [英] Firestore - Creating a copy of a collection

查看:28
本文介绍了Firestore - 创建集合的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个名为草稿"的集合,其中包含多个文档,每个文档都有一个自动 ID.每个文档都包含字段名称"和详细信息".每个文档都显示在nameLabel"和detailsLabel"下的 tableViewCell 中.我想要做的是当用户单击 First viewController 屏幕顶部的按钮时,创建集合Drafts"的副本并将其粘贴到名为Messages"的新集合名称下.这个集合然后引用第二个 viewControllers tableViewCells 就像在第一个 ViewController 上一样,只是这次它在集合消息"下被引用.做了一些研究后,我有一个模糊的倾向,即答案使用云函数来创建集合的副本并将其粘贴到新的集合名称中.然而,对于编码和 firebase 来说相对较新,我不知道如何做到这一点,也不知道这是否是正确的解决方案.请有人帮忙,非常感谢任何帮助!!谢谢!

So I have a collection called "Drafts" which contains multiple documents each with an auto ID. Each document contains the fields "name" and "details". Each document is displayed in a tableViewCell under "nameLabel" and "detailsLabel". What I would like to do is when the user clicks on a button at the top of the screen of the First viewController, a copy of the collection "Drafts" is created and pasted under a new collection name called "Messages". This collection is then referencing the Second viewControllers tableViewCells just like on the First ViewController only this time its being referenced under the collection "Messages". Having done some research I have a vague inclination that the answer uses cloud functions to essentially create a copy of the collection and paste it with a new collection name. However being relatively new to coding and firebase, I have no idea how to do this and don't know if this is the correct solution. Please may someone help, any help is greatly appreciated!! Thanks!

第一个视图控制器

func loadDrafts() {

    let userRef = db.collection("Users").document(user!)

    let draftsRef = userRef.collection("Drafts")

    exercisesRef.getDocuments { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            if let snapshot = querySnapshot {
                for document in snapshot.documents {
                    let data = document.data()
                    let name = data["name"] as? String ?? ""
                    let details = data["details"] as? String ?? ""
                    let newDrafts = DraftMessages(name: name, details: details)
                    self.array.append(newDrafts)
                }
                self.tableView.reloadData()
            }
        }
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! DraftsCell

    cell.nameLabel.text = array[indexPath.row].name
    cell.detailsLabel.text = array[indexPath.row].details

    return cell
}

@IBAction func goButton(_ sender: UIButton) {

\\ Add code here to create copy of previous collection "Drafts" and paste in new collection "Messages"

}

第二个视图控制器

func loadData() {

    let userRef = db.collection("Users").document(user!)

    userRef.collection("Messages").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let data = document.data()
                let name = data["name"] as? String ?? ""
                let details = data["details"] as? String ?? ""
                let newMessages = Messages(name: name, details: details)
                self.array.append(newMessages)
            }
            self.tableView.reloadData()
        }
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MessagesCell

    cell.nameLabel.text = array[indexPath.row].name
    cell.detailsLabel.text = array[indexPath.row].details

    return cell

}

推荐答案

这是我的工作解决方案.非常感谢弗兰克斯的帮助!

Here is my working solution. Many thanks to Franks for the help!

@IBAction func goButton(_ sender: UIButton) {

    let userRef = db.collection("Users").document(user!)

    let draftsRef = userRef.collection("Drafts")

    draftsRef.getDocuments { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            if let snapshot = querySnapshot {
                for document in snapshot.documents {
                    let data = document.data()
                    let batch = self.db.batch()
                    let docset = querySnapshot

                    let messagesRef = userRef.collection("Messages").document()

                    docset?.documents.forEach {_ in batch.setData(data, forDocument: messagesRef)}

                    batch.commit(completion: { (error) in
                        if let error = error {
                            print("\(error)")
                        } else {
                            print("success")
                        }
                    })
                }
            }
        }
    }
}

为 Vaibhav Jhaveri

这个函数(希望)同时复制获取的文档数据和该文档子集合中的数据.(不过我还没有测试过)

This function (hopefully) both duplicates the fetched documents data and the data inside of that documents subcollection. (I have not tested this though)

func duplicate() {
    let userRef = db.collection("Users").document(userID)
    let batch = self.db.batch()

    let draftsRef = userRef.collection("Drafts")
    draftsRef.getDocuments { (snapshot, err) in
        if let err = err {
            print(err.localizedDescription)
            return
        }

        guard let snapshot = snapshot else { return }

        snapshot.documents.forEach({ (document) in
            let data = document.data()
            let messageID = UUID().uuidString

            let messagesRef = userRef.collection("Messages").document(messageID)
            batch.setData(data, forDocument: messagesRef, merge: true)

            let yourSubCollectionRef = draftsRef.document(document.documentID).collection("yourSubCollection")
            yourSubCollectionRef.getDocuments(completion: { (subSnapshot, subErr) in
                if let subErr = subErr {
                    print(subErr.localizedDescription)
                    return
                }

                guard let subSnapshot = subSnapshot else { return }

                subSnapshot.documents.forEach({ (subDocument) in
                    let subData = subDocument.data()
                    let subDocID = UUID().uuidString

                    let yourNewSubCollectionRef = userRef.collection("Messages").document(messageID).collection("yourSubCollection").document(subDocID)
                    batch.setData(subData, forDocument: yourNewSubCollectionRef, merge: true)
                })
            })
        })

        batch.commit()
    }
}

这篇关于Firestore - 创建集合的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆