虽然有一个完美的答案,但 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
查看文档添加文档 https://firebase.google.com/docs/firestore/manage-data/add-data#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
}
}