使用 Swift 5 获取 Firestore 中字段的旧值

Getting old value of field in Firestore with Swift 5

我正在尝试获取在 Firestore 中更改的字段的旧值。有什么方法可以访问字段更改后的先前值吗?这是我当前的代码,我想访问 .modified 下的旧 nickName 并打印出新 nickName 和旧

是什么。

db.collection("cities").whereField("state", isEqualTo: "CA").addSnapshotListener { querySnapshot, error in
    guard let snapshot = querySnapshot else {
        print("Error fetching snapshots: \(error!)")
        return
    }
    snapshot.documentChanges.forEach { diff in
        if (diff.type == .added) {
            print("New city: \(diff.document.data())")
        let nickName = myData["nickName"] as? String ?? ""
        }
        if (diff.type == .modified) {
            let nickName = myData["nickName"] as? String ?? ""
        }
        if (diff.type == .removed) {
            let nickName = myData["nickName"] as? String ?? ""
        }
    }
}

遗憾的是,这不是 Firestore 的功能。您可以做的是拥有另一个字段 oldNickName 并使用 Firebase Functions,当 nickName 字段更改时自动更新它。

最好的解决方案是将 nickName 存储在本地,这样当 nickName 更改时,您可以引用本地变量,访问数据库中新更新的变量和之前的 nickName本地。这是更新后的代码:

var nickNames = [String : String]()
db.collection("cities").whereField("state", isEqualTo: "CA").addSnapshotListener { snapshot, error in
    guard error == nil, let snapshot = snapshot?.documentChanges else { return }
    snapshot.forEach {
        let document = [=10=].document
        let documentID = document.documentID
        let nickName = document.get("nickName") as? String ?? "Error"
        switch [=10=].type {
            case .added:
                print("New city: \(document.data())")
                nickNames[documentID] = nickName
            case .modified:
                print("Nickname changed from \(nickNames[documentID]) to \(nickName)")
                nickNames[documentID] = nickName
            case .removed:
                print("City removed with nickname \(nickNames[documentID])")
                nickNames.removeValue(forKey: documentID)
        }
    }
}

nickNames 是一个具有键 cityID 和值 nickName 的字典。这段代码写在Swift 5.