目前我已经做到了,当用户单击按钮时,FirstCollection 中的所有文档都会复制到名为 SecondCollection 的集合中,效果很好!
我现在想做的是使用新创建的名为 SecondCollection 的集合中所有文档中字段 (numberValue) 的 Int 值。然后使用这些值在文档的名为“SecondSubCollection”的子集合中创建多个文档。
例如,假设一个文档中的 numberValue 为 3,我想执行批量请求并在文档的名为“SecondSubCollection”的子集合下创建 3 个文档。然后通过一个请求对 SecondCollection 中的所有文档执行此操作。
请参阅下面的代码,了解我到目前为止所得到的内容。当我按下按钮时,它只在每个子集合中创建一个文档,这并没有按照我想要的方式工作。我想让它创建多个文档(如果文档中的 numberValue 为 3,则应该在文档的子集合中创建 3 个文档)。
希望这更有意义!任何帮助将不胜感激,谢谢!!
代码
@IBAction func goButton(_ sender: UIButton) {
let userRef = db.collection("Users").document(user!)
userRef.collection("SecondCollection").document(firstID).setData(["name" : "name"]) {
error in
if let error = error {
print("Error adding document: \(error.localizedDescription)")
} else {
print("Document added with ID")
}
}
let firstRef = userRef.collection("FirstCollection")
firstRef.getDocuments { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
if let snapshot = querySnapshot {
for document in snapshot.documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let numberValue = data["numberValue"] as? Int ?? Int()
let batch = self.db.batch()
let docset = querySnapshot
let integerArray = [Int](1...numberValue)
let secondID = UUID().uuidString
let secondRef = userRef.collection("SecondCollection").document(secondID)
docset?.documents.forEach {_ in batch.setData(["name" : name, "numberValue" : numberValue], forDocument: secondRef)}
\\ the code that isn't working properly at the moment
let secondSubRef = secondRef.collection("SecondSubCollection").document()
docset?.documents.forEach {integerArray in batch.setData(["value" : Int], forDocument: secondSubRef)}
batch.commit(completion: { (error) in
if let error = error {
print("\(error)")
} else {
print("success")
}
})
}
}
}
}
}
现在正在做什么
第一个集合:
- 文档ID。
- 姓名:姓名。
- 数值:3。
- 文档ID。
- 姓名:姓名。
- 数值:2。
- 文档ID。
第二个集合:
- 文档ID。
- 姓名:姓名。
- 数值:3。
- 第二子集合。
- 文档ID。
- 值:1。
- 文档ID。
- 文档ID。
- 姓名:姓名。
- 数值:2。
- 第二子集合。
- 文档ID。
- 值:1。
- 文档ID。
- 文档ID。
我想做什么
第一个集合:
- 文档ID。
- 姓名:姓名。
- 数值:3。
- 文档ID。
- 姓名:姓名。
- 数值:2。
- 文档ID。
第二个集合:
- 文档ID。
- 姓名:姓名。
- 数值:3。
- 第二子集合。
- 文档ID。
- 值:1。
- 文档ID。
- 值:2。
- 文档ID。
- 值:3。
- 文档ID。
- 文档ID。
- 姓名:姓名。
- 数值:2。
- 第二子集合。
- 文档ID。
- 值:1。
- 文档ID。
- 值:2。
- 文档ID。
- 文档ID。
最佳答案
这是我的工作(简化)解决方案:(非常感谢杰伊的巨大帮助!)
@IBAction func goButton(_ sender: UIButton) {
let userRef = db.collection("Users").document(user!)
let array = [1, 2, 3]
array.forEach { number in
let batch = self.db.batch()
let docRef = userRef.collection("FirstCollection").document()
batch.setData(["numberValue" : number], forDocument: docRef)
}
batch.commit(completion: { (error) in
if let error = error {
print("\(error)")
} else {
print("success")
}
})
}
关于swift - Firestore - 使用 querySnaphot 中的 Int 值一次创建多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50826522/