【发布时间】:2018-06-27 00:08:01
【问题描述】:
这是我的数据结构:
我有一个尝试从 Cloud Firestore 访问数据的 ios 应用。我已成功检索完整文档和查询文档。但是我需要访问特定文档中的特定字段。我将如何进行调用以快速从 Firestore 中检索一个字段的值?任何帮助,将不胜感激。
【问题讨论】:
标签: ios swift firebase google-cloud-firestore
这是我的数据结构:
我有一个尝试从 Cloud Firestore 访问数据的 ios 应用。我已成功检索完整文档和查询文档。但是我需要访问特定文档中的特定字段。我将如何进行调用以快速从 Firestore 中检索一个字段的值?任何帮助,将不胜感激。
【问题讨论】:
标签: ios swift firebase google-cloud-firestore
没有任何 API 可以使用任何 Web 或移动客户端 SDK 从文档中提取单个字段。当您使用getDocument() 时,始终会获取整个文档。这意味着也没有办法使用安全规则来保护文档中的单个字段而不是其他字段。
如果您想尽量减少通过网络传输的数据量,您可以将该单独的字段放在主文档的子集合中自己的文档中,然后您可以单独请求该文档。
服务器 SDK 可以使用 select() 之类的方法,但您显然需要在后端编写代码并从客户端应用程序调用它。
【讨论】:
_projection 属性。我试图为其分配一个字段列表,但它引发了以下异常:VIRTUALENV/env/lib/python3.7/site-packages/google/cloud/firestore_v1/base_query.py in _normalize_projection(projection) ... 684 if projection is not None: ... --> 686 fields = list(projection.fields) ... AttributeError: 'list' object has no attribute 'fields'
其实有办法,使用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")
}
}
【讨论】:
//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);
});
【讨论】:
这实际上非常简单,并且使用内置的 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")
}
}
【讨论】: