![](/img/trans.png)
[英]Interacting with firebase firestore from firebase cloud functions
[英]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.