Add a Document's Document ID to Its Own Firestore Document - Swift 4

前端 未结 1 1252
一整个雨季
一整个雨季 2021-02-15 20:52

How do I go about adding the document ID of a document I just added to my firestore database, to said document?

I want to do this so that when a user retrieves a \"ride\

相关标签:
1条回答
  • 2021-02-15 21:18

    While there is a perfectly fine answer, FireStore has the functionality you need built in, and it doesn't require two calls to the database. In fact, it doesn't require any calls to the database.

    Here's an example

        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
    

    See the documentation Add a Document for more info.

    In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():

    You may want to consider a slightly different approach. You can obtain the document ID in the closure following the write as well. So let's give you a cool Ride (class)

    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
        }
    }
    

    and then some code to create a ride, write it out and leverage it's auto-created 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
            }
        }
    
    0 讨论(0)
提交回复
热议问题