将文档的文档ID添加到其自己的Firestore文档中-Swift 4

时间:2019-01-22 04:33:03

标签: ios swift firebase google-cloud-firestore id

如何将刚刚添加到Firestore数据库中的文档的文档ID添加到所述文档中?

我想这样做,以便当用户检索“乘车”对象并选择预订时,我可以知道他们已经预订了哪个特定的游乐设施。

我面临的问题是,在创建文档ID之前,您无法获得它,因此将其添加到所述文档中的唯一方法是创建文档,读取其ID,然后编辑文档添加ID。大规模地,这将创建所需数量两倍的服务器调用。

是否有标准方法可以做到这一点?还是一个简单的解决方案,可以知道用户预订了哪个“乘车”并在数据库中进行相应的编辑?

struct Ride {
    var availableSeats: Int
    var carType: String
    var dateCreated: Timestamp
    var ID: String // How do I implement this?
}


func createRide(ride: Ride, completion: @escaping(_ rideID: String?, _ error: Error?) -> Void) {
    // Firebase setup
    settings.areTimestampsInSnapshotsEnabled = true
    db.settings = settings

    // Add a new document with a generated ID
    var ref: DocumentReference? = nil
    ref = db.collection("rides").addDocument(data: [
        "availableSeats": ride.availableSeats,
        "carType": ride.carType,
        "dateCreated": ride.dateCreated,
        "ID": ride.ID,
    ]) { err in
        if let err = err {
            print("Error adding ride: \(err)")
            completion(nil, err)
        } else {
            print("Ride added with ID: \(ref!.documentID)")
            completion(ref?.documentID, nil)
            // I'd currently have to use this `ref?.documentID` and edit this document immediately after creating. 2 calls to the database.
        }
    }
}

3 个答案:

答案 0 :(得分:2)

尽管有一个很好的答案,但FireStore具有您所需的内置功能,并且不需要两次调用数据库。实际上,它不需要任何对数据库的调用。

这是一个例子

    let testRef = self.db.collection("test_node")
    let someData = [
        "child_key": "child_value"
    ]

    let aDoc = testRef.document() //this creates a document with a documentID
    print(aDoc.documentID) //prints the documentID, no database interaction
    //you could add the documentID to an object etc at this point
    aDoc.setData(someData) //stores the data at that documentID

有关更多信息,请参见文档Add a Document

  

在某些情况下,使用   自动生成的ID,然后在以后使用参考。对于此用例,   您可以调用doc():

您可能要考虑略有不同的方法。您也可以在写入后在闭包中获取文档ID。因此,让我们给您一个酷骑(课程)

class RideClass {
    var availableSeats: Int
    var carType: String
    var dateCreated: String
    var ID: String

    init(seats: Int, car: String, createdDate: String) {
        self.availableSeats = seats
        self.carType = car
        self.dateCreated = createdDate
        self.ID = ""
    }

    func getRideDict() -> [String: Any] {
        let dict:[String: Any] = [
            "availableSeats": self.availableSeats,
            "carType": self.carType,
            "dateCreated": self.dateCreated
        ]
        return dict
    }
}

然后是一些代码来创建游乐设施,将其写出并利用其自动创建的documentID

    var aRide = RideClass(seats: 3, car: "Lincoln", createdDate: "20190122")

    var ref: DocumentReference? = nil
    ref = db.collection("rides").addDocument(data: aRide.getRideDict() ) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {
            aRide.ID = ref!.documentID
            print(aRide.ID) //now you can work with the ride and know it's ID
        }
    }

答案 1 :(得分:1)

我相信,如果您使用UUID框架提供的Swift内置ID生成器,称为Foundation,这将使您可以做自己想做的事情。请参阅以下代码,了解我的建议更改。同样通过这种方式,当您首次初始化“ Ride”结构时,可以生成其ID变量,而不是在函数内部进行操作。这是我在整个应用程序中生成唯一ID的方式,并且效果很好!希望这会有所帮助!

struct Ride {
    var availableSeats: Int
    var carType: String
    var dateCreated: Timestamp
    var ID: String
}


func createRide(ride: Ride, completion: @escaping(_ rideID: String, _ error: Error?) -> Void) {
    // Firebase setup
    settings.areTimestampsInSnapshotsEnabled = true
    db.settings = settings

    // Add a new document with a generated ID
    var ref: DocumentReference? = nil
    let newDocumentID = UUID().uuidString
    ref = db.collection("rides").document(newDocumentID).setData([
        "availableSeats": ride.availableSeats,
        "carType": ride.carType,
        "dateCreated": ride.dateCreated,
        "ID": newDocumentID,
    ], merge: true) { err in
        if let err = err {
            print("Error adding ride: \(err)")
            completion(nil, err)
        } else {
            print("Ride added with ID: \(newDocumentID)")
            completion(newDocumentID, nil)
        }
    }
}

答案 2 :(得分:1)

这是我的解决方案,就像一个魅力

    let opportunityCollection = db.collection("opportunities")
    let opportunityDocument = opportunityCollection.document()
    let id = opportunityDocument.documentID

    let data: [String: Any] = ["id": id,
                               "name": "Kelvin"]

    opportunityDocument.setData(data) { (error) in
        if let error = error {
            completion(.failure(error))
        } else {
            completion(.success(()))
        }
    }