我正在尝试获取在FireStore中更改字段时字段的旧值。是否有任何方法可以访问字段更改后的前一个值?这是我当前的代码,我想访问nickName下的旧.modified并打印出新的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函数,在更改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 = $0.document
        let documentID = document.documentID
        let nickName = document.get("nickName") as? String ?? "Error"
        switch $0.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是一个带有keycityID和valuenickName的字典。这段代码是用Swift 5编写的。

关于swift - 使用Swift 5在Firestore中获取旧字段值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55443496/

10-17 00:56