如何减少 Firestore 的文档读取

Cha*_*Jie 5 javascript nosql firebase google-cloud-functions google-cloud-firestore

我正在将 Firestore (我是新手)用于小型 Web 应用程序。目前,每次刷新或转到另一个页面时,该函数都会检索 Firestore 中的所有文档。但它检索的数据不会经常改变,

有没有一种方法可以让我检索所有数据,而无需阅读任何文档?

我目前正在使用这些函数来检索数据

firebase
.firestore()
.collection("products")
.then((snapshot) => {
       snapshot.forEach((docs) => {
       });
});



firebase
.firestore()
.collection("products")
.where("prodID", "==", prodID)
.then((snapshot) => {
       snapshot.forEach((docs) => {
       });
});
Run Code Online (Sandbox Code Playgroud)

ant*_*vet 4

这取决于您的应用程序。
但减少这种情况的一种方法是从缓存中检索它们。
根据文档(https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Source)你可以做类似的事情

function getData() {
   firebase
   .firestore()
   .collection("products")
   .get({source: "cache"})
   .then((snapshot) => {
         if (!snapshot.exist) return getServerData()
         snapshot.forEach((docs) => {
       });
  });
}

function getServerData() {
   firebase
   .firestore()
   .collection("products")
   .get()
   .then((snapshot) => {
         snapshot.forEach((docs) => {
       });
  });
}   
Run Code Online (Sandbox Code Playgroud)

  • 正确的链接是 https://firebase.google.com/docs/reference/js/v8/firebase.firestore.GetOptions (3认同)