将文档的文档ID添加到其自己的Firestore文档中-Swift 4 [英] Add a Document's Document ID to Its Own Firestore Document - Swift 4

查看:62
本文介绍了将文档的文档ID添加到其自己的Firestore文档中-Swift 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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" object and chooses to book it, I can know which specific ride they've booked.

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

The problem that i'm facing is that you can't get the document ID until after it's created, so the only way to add it to said document would be to create a document, read its ID, then edit the document to add in the ID. At scale this would create twice as many server calls as desired.

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

Is there a standard way to do this? Or a simple solution to know which "ride" the user booked and edit it accordingly in the database?

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

推荐答案

虽然有一个很好的答案,但FireStore具有内置的功能,不需要两次调用数据库.实际上,它不需要任何对数据库的调用.

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.

这是一个例子

    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.

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

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():

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

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

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

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

这篇关于将文档的文档ID添加到其自己的Firestore文档中-Swift 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆