在Firestore中删除文档并将文档添加到集合时出错

时间:2019-07-26 13:43:32

标签: swift google-cloud-firestore

我正在尝试用Firestore中的一组新文档替换集合中的所有文档。我正在为iOS应用程序使用Swift。我收到以下错误:***由于未捕获的异常'FIRIllegalStateException'而终止应用程序,原因:'调用提交后将无法再使用写批处理。'

我在做什么错了?

下面是我的代码:

    let oldDb = Firestore.firestore()
    let oldSettings = oldDb.settings
    oldSettings.areTimestampsInSnapshotsEnabled = true
    oldDb.settings = oldSettings
    let oldBatch = oldDb.batch()

    let docRef = oldDb.collection("users").document(currentUserId).collection("friends")
    docRef.getDocuments(completion: { (list, error) in
        if let list = list {
            for document in list.documents {
                oldBatch.deleteDocument(document.reference)
            }
        } else {
            print("Document does not exist in cache: \(currentUserId)")
        }
    })

   oldBatch.commit()
    { err in
            if let err = err {
                print("Error deleting existing contacts in firestore: \(err)")
            }
    }

    let db = Firestore.firestore()
    let settings = db.settings
    settings.areTimestampsInSnapshotsEnabled = true
    db.settings = settings
    let batch = db.batch()

    for contact in contactsBack {
        let requestRef = db.collection("users").document(currentUserId).collection("friends").document(contact.phoneNumbers[0].value.stringValue)
        batch.setData([:], forDocument: requestRef)
        batch.updateData(["firstName": contact.givenName], forDocument: requestRef)
        batch.updateData(["lastName": contact.familyName], forDocument: requestRef)
    }
    batch.commit()
    { err in
            if let err = err {
                print("Error adding contact to firestore: \(err)")
            }
    }

0 个答案:

没有答案