这是我的数据结构:
我有一个试图从Cloud Firestore访问数据的ios应用。我成功地检索了完整的文档并查询了文档。但是,我需要访问特定文档中的特定字段。我如何拨打电话,从swift中的Firestore中检索一个字段的值?任何帮助,将不胜感激。
答案 0 :(得分:7)
没有API只从文档中提取单个字段。使用getDocument()时始终会提取整个文档。这意味着也没有办法使用安全规则来保护文档中的单个字段的方式与其他字段不同。
如果您尝试最小化线路上的数据量,可以将该单独字段放在主文档的子集合中的自己的文档中,并且可以单独请求一个文档。
答案 1 :(得分:0)
这实际上非常简单,并且使用内置的Firebase API可以实现。
let docRef = db.collection("users").document(name)
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let property = document.get(field)
} else {
print("Document does not exist in cache")
}
}
答案 2 :(得分:0)
实际上,有一种方法可以使用Firebase本身提供的示例代码
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let property = document.get('fieldname')
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
答案 3 :(得分:-1)
答案 4 :(得分:-1)
//this is code for javascript
var docRef = db.collection("users").doc("ID");
docRef.get().then(function(doc) {
if (doc.exists) {
//gives full object of user
console.log("Document data:", doc.data());
//gives specific field
var name=doc.get('name');
console.log(name);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});