![](/img/trans.png)
[英]How to only send Algolia specific fields from a document in Firestore
[英]Firestore - get specific fields from document
我想在 Firestore 中保存文章或筆記及其各自的字段:
但是當我顯示文章列表時,我不需要“內容”字段(以節省帶寬)。 我已經讀過(也許我錯了),無法使用 Firestore 進行查詢以僅從文檔中獲取特定字段。
如果從文章中獲取特定列(沒有其內容)是正常的 SQL,它將類似於:
SELECT title, creation_date, ...
FROM table_name;
所以我選擇將兩個根級集合的內容分開(為了靈活性和可擴展性)
文章集:
- `articles` [collection]
- `ARTICLE_ID` [document]
- `creatorId` [field]
- `title` [field]
- `date` [field]
- `owners` [obj field]
- {user1_id}: true
- {user2_id}: true
...
內容收集:
- `contents` [collection]
- `{ARTICLE_ID}` [document]
- `content` [field]
實時獲取文章列表:
firebase.firestore().collection('articles')
.where(`owners.${user.uid}`, '==', true)
.onSnapshot(querySnapshot => {
const articles = []
querySnapshot.forEach((doc) => {
articles.push({
id: doc.id,
...doc.data()
})
})
// do something with articles array
})
要在另一個視圖中顯示並獲取整篇文章及其內容:
const db = firebase.firestore()
const articleRef = db.collection('articles').doc(articleId)
const contentRef = db.collection('contents').doc(articleId) // same Id as article
articleRef.get().then(articleDoc => {
if (articleDoc.exists) {
contentRef.get().then(contentDoc => {
if (contentDoc.exists) {
const article = {
...articleDoc.data(),
...contentDoc.data()
}
// full article obj
}
})
}
})
您是否認為最好同時執行兩個查詢(getArticle 和 getContent)並使用 Promise.all() 等待而不是像我那樣嵌套查詢?
有沒有更好的方法可以通過一個查詢或更有效地獲取文章及其內容? 一些提示或想法?
非常感謝您提前!
這兩種方法都沒有比另一種更有針對性。 但是有一些關鍵的區別。
嵌套讀取時,第二次只讀在第一次讀取完成后開始。 當你使用Promise.all()
兩個讀取同時開始,因此可以(部分)並行運行。
另一方面:當你使用Promise.all()
你的完成處理程序(你在then()
運行的代碼)將不會執行,直到兩個文檔都已加載。 如果嵌套調用,則可以在加載第一個文檔后更新UI。
最后,差異可能很小。 但由於它們對您的用例可能很重要,因此請測量結果,看看哪種方法最適合您。
根據Firestore Query.select文檔,您應該能夠選擇所需的字段。
let collectionRef = firestore.collection('col');
let documentRef = collectionRef.doc('doc');
return documentRef.set({x:10, y:5}).then(() => {
return collectionRef.where('x', '>', 5).select('y').get();
}).then((res) => {
console.log(`y is ${res.docs[0].get('y')}.`);
});
對於靜態內容(如文章),Firebase Hosting將是您最好的選擇。 例如,如果你看一下AMP-HTML ,它們就可以為超快的頁面加載提供支持,並突出顯示邊緣緩存的優勢。 Firebase托管廣告也支持全局邊緣緩存 。
Firestore和Firebase實時數據庫是數據庫引擎。 這些不是提供文章的適當工具。
為了從 Firestore 文檔(版本 9)輸出單個字段 - 例如文章集合中的“標題”,您可以使用以下代碼片段:
const q = query(collection(db, 'articles'))
let results = [];
await getDocs(q);
results = getLocation.docs.map((doc) => doc.data()['title']);
results.sort()
結果數組將只包含標題字段,按字母順序排序(請注意,您必須引用 Firestore 數據庫並從 Firestore 導入“getDocs”、“query”和“collection”模塊)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.