2017-10-19 16 views
1

ネストされた約束なしに自分のコードを読み書きする方法を少し混乱させています。オブジェクトの書き込み時に、そのオブジェクトにフラグが設定されている場合は、その関連するオブジェクトを新しいカウントで更新します。私には2つの問題があります。クラウド関数の読み書きを扱う方法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); 
      }) 
    }; 

}); 

を返すことになってプラスそれは私が何か... nilを返すように望んでいるのですか?

+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. は1あなたが何かを返したい.catch()
関連する問題