2017-10-19 69 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()