繁体   English   中英

如何从 Swift 中的 Cloud FireStore Firebase 访问特定字段

[英]How to access a specific field from Cloud FireStore Firebase in Swift

这是我的数据结构:

数据结构

我有一个 ios 应用程序正在尝试从 Cloud Firestore 访问数据。 我已成功检索完整文档和查询文档。 但是我需要访问特定文档中的特定字段。 我将如何进行调用以仅从 swift 中的 Firestore 中检索一个字段的值? 任何帮助,将不胜感激。

没有任何 API 可以使用任何 Web 或移动客户端 SDK 从文档中获取单个字段。 当您使用getDocument()时,总是会获取整个文档。 这意味着也没有办法使用安全规则来保护文档中的单个字段,而不是其他字段。

如果您想尽量减少通过网络传输的数据量,您可以将该单独的字段放在主文档的子集合中的自己的文档中,并且您可以单独请求该文档。

另请参阅此讨论主题

服务器 SDK 可以使用select()等方法,但您显然需要在后端编写代码并从客户端应用程序调用它。

这实际上非常简单,并且可以使用内置的 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")
            }
        }

其实有一个方法,使用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")
    }
}

我想我迟到了,但经过一些广泛的研究,有一种方法可以从 firestore 获取特定字段。 我们可以使用select关键字,您的查询将类似于(我使用集合作为通用方法):

const result = await firebase.database().collection('Users').select('name').get();

我们可以在哪里访问result.docs以进一步检索返回的过滤结果。 谢谢!

//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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM