2017-10-19 64 views
1

我對如何重構我的代碼以讀取和寫入沒有嵌套的承諾有點困惑。在寫入對象時,如果該對象設置了標誌,我想用新的計數更新其「相關」對象。我有兩個問題。如何處理雲功能中的讀取和寫入Firestore

1)嵌套承諾從讀取然後寫入。 2)那我應該回到

exports.updateRelationshipCounts = functions.firestore 
    .document('masterProduct/{nfCode}').onWrite((event) => { 

    //on writing of record: 

    var newProduct = event.data.data(); 
    if (newProduct.isGlutenFreeYN === 'Y') { 
     console.log('Gluten Free'); 

     //Update GF count in the Brand Object: 

     var db = admin.firestore(); 
     var docRef = db.collection("masterBrand").doc(newProduct.brandNFCode); 
     var doc = docRef.get() 
      .then(doc => { 

       doc.glutenFreeCount = doc.glutenFreeCount + 1 


       docRef.set(newProduct.brand) 
        .then(function() { 
         console.log("Document successfully written!"); 
        }) 
        .catch(function (error) { 
         console.error("Error writing document: ", error); 
        }); 

       }) 
      .catch(err => { 
        console.log('Error getting document', err); 
      }) 
    }; 

}); 

加上它要我返回的東西......零?

+0

誰要你返回的東西? '.onWrite()'事件處理程序? [doc here](https://firebase.google.com/docs/functions/firestore-events)中的'.onWrite()'處理程序都不顯示任何返回的內容。 – jfriend00

回答

4

您可以使用鏈接並消除一些嵌套。

exports.updateRelationshipCounts = functions.firestore 
    .document('masterProduct/{nfCode}').onWrite((event) => { 
    //on writing of record: 
    var newProduct = event.data.data(); 
    if (newProduct.isGlutenFreeYN === 'Y') { 
     console.log('Gluten Free'); 
     //Update GF count in the Brand Object: 

     var db = admin.firestore(); 
     var docRef = db.collection("masterBrand").doc(newProduct.brandNFCode); 
     docRef.get().then(doc => { 
      doc.glutenFreeCount = doc.glutenFreeCount + 1 
      return docRef.set(newProduct.brand); 
     }).then(() => { 
      console.log("document successfully written); 
     }).catch(err => { 
      // will log all errors in one place 
      console.log(err); 
     }); 
    } 
}); 

變化:

  1. 鏈的頂層,而不是越來越深嵌套。
  2. 返回嵌套的承諾,以便它們正確鏈接。
  3. 合併錯誤處理程序,以一個.catch()