【发布时间】:2018-03-30 23:32:17
【问题描述】:
我对 Cloud Firestore 还是很陌生(不是吗?),我已经使用 Node.js 中的管理 SDK 向我的数据库添加了一些数据。它显示在控制台上,但在文档下显示“此文档不存在,它不会出现在查询或快照中。”我不确定这是为什么?截图如下:
【问题讨论】:
标签: node.js database nosql google-admin-sdk google-cloud-firestore
我对 Cloud Firestore 还是很陌生(不是吗?),我已经使用 Node.js 中的管理 SDK 向我的数据库添加了一些数据。它显示在控制台上,但在文档下显示“此文档不存在,它不会出现在查询或快照中。”我不确定这是为什么?截图如下:
【问题讨论】:
标签: node.js database nosql google-admin-sdk google-cloud-firestore
根据@rithvik-ravikumar 的建议,使用 Firestore 批处理(Swift 版本):
首先我们在/users/:id/issues 下创建新文档并更新/users/:id 上的属性updatedAt 以使其“可查询”。
func saveInBatch() {
let db = Firestore.firestore()
var issueReportData: [String: Any] = [:] // Some data you want to store.
let batch = db.batch()
let userDocRef = db.collection("users").document("_firebase_user_id_goes_here_")
let issueDocRef = userDocRef.collection("issues").document() // This will be a new document.
// This is needed in order to make document "queryable".
batch.setData(["updatedAt": FieldValue.serverTimestamp()], forDocument: userDocRef)
batch.setData(issueReportData, forDocument: issueDocRef)
batch.commit() { err in
if let err = err {
print("Error writing batch \(err)")
} else {
print("Batch write succeeded.")
}
}
}
现在我们可以在/users 路径获取文档。
func fetchUsers() {
let db = Firestore.firestore()
db.collection("users").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
debugPrint("Found \(querySnapshot!.documents.count) documents")
for document in querySnapshot!.documents {
let data = document.data()
print("\(document.documentID) => \(data)")
}
}
}
}
【讨论】:
我想这就是你们都在寻找的答案: 当您创建如下文档时:
let ref = Firestore.firestore().collection("users").document().collection("data")
您没有使用自动生成的 ID 为该文档创建实际位置。 而是像这样添加一个空字段:
let tempRef = Firestore.firestore().collection("users").addDocument(data: ["dummy":"text"])
let id = ref.documentId
let ref = Firestore.firestore.collection("users").document(id).collection("data")
我试过了,现在可以正常工作了。
【讨论】:
要认识到的关键是,仅仅因为您在root_collection > root_doc > sub_collection > sub_doc 创建了一个文档,并不意味着实际上在root_collection > root_doc 有一个文档。
所以为了向您显示... > Events > 10-12-2017 > Phase Data 下的文档,控制台显示10-12-2017 就好像它是一个文档,但它让您知道该位置实际上没有文档。所以如果你查询... > Events下的文档,10-12-2017就不会出现。
【讨论】:
root_collection > root_doc > sub_collection > sub_doc的代码时动态创建root_doc
mkdirs()?