如何解决如何从Firebase获取按变量排序的文档不知道DocumentName
我已成功从Firestore获取文档。
下一个问题是我应该如何更改代码,以便获得添加到集合中的最新文档。
我知道我可以使用.order(by: String)
或.limit(to: Int)
之类的参数,但是我不知道 WHERE 和 HOW
我也在Firestore文档中寻找答案,但是只是说了如何以及在某些特定示例中必须使用什么功能。
我添加了该函数,该函数应该会得到这个未知的文档以及有关数据库模型外观的图片。
代码段:
func getSingleproperty() {
var desiredProperty: String!
let docRef = db.collection("UnKnownErrorMessages").document()
docRef.getDocument { (document,error) in
if let document = document,document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
//Print all data in the document
print("Document data: \(dataDescription)")
if let allPropertiesInDocument = document.data() {
let nameOfPropertyIwantToRetrieve = "read"
if let selectedProperty = allPropertiesInDocument[nameOfPropertyIwantToRetrieve] {
desiredProperty = selectedProperty as? String
}
}
//Print exact the data that is in 'nameOfPropertyIwantToRetrieve' specified
print("Value of desiredProperty is \(desiredProperty.description)")
} else {
print("Document does not exist \(error.debugDescription)")
}
}
}
Firestore database model(红色框中的变量,是我要排序的变量)
解决方法
您无法从Firestore文档中读取单个密钥。您总是会得到整个文档。
要访问最新文档,请参见https://stackoverflow.com/a/54178993
,这是如何从Firestore数据库中检索值的真实示例。在这种情况下,我已使用this page上Firestore文档中“添加数据”下的代码为您定制了查询。
请尝试以下操作:
func getSingleproperty() {
var desiredProperty: String!
let docRef = db.collection("UnKnownErrorMessages").document("Error1234")
docRef.getDocument { (document,error) in
if let document = document,document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
if let allPropertiesInDocument = document.data() {
let nameOfPropertyIwantToRetrieve = "errorMessage"
if let selectedProperty = allPropertiesInDocument[nameOfPropertyIwantToRetrieve] {
desiredProperty = selectedProperty as? String
}
}
print("Value of desiredProperty is \(desiredProperty)")
} else {
print("Document does not exist")
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。