2017-06-18 6 views
2

クライアントがpush()を呼び出したときに生成されたキーを参照する場合は、 。Firebaseのクラウド関数:ちょうどプッシュされたリスト内のキーを参照する方法

/providerApps/{UID}/は、予定ノードのリストへの私のパスなので、各予定ノードは/providerApps/{UID}/someKeyです。

は、私は「リストに新しい項目」、プッシュ()を添加したものを必要とするので、私は、私は、キーを注文すると、単に最後のものを得ることができると思ったが、それは動作しません:

// (Try to) Listen for new appointments at /providerApps/{pUID} 
// and store the appointment at at /clientApps/{cUID} 
// cUID is in the new appointment node 
exports.storeNewAppForClient = functions.database.ref("/providerApps/{UID}").onWrite(event => { 

     // Exit when the data is deleted. 
     if (!event.data.exists()) { 
     console.log("deletion -> exiting"); 
     return; 
     } 

     const pUID = event.params.UID; 
     const params = event.params; 
     console.log("params: ", params); 

     const firstAppVal = event.data.ref.orderByKey().limitToLast(1).val(); 
     // TypeError: event.data.ref.orderByKey(...).limitToLast(...).val is not a function 

     const date = firstAppVal["dateStr"]; 
     const cUID = firstAppVal["clientUID"]; 

    return event.data.ref.root.child("clientApps").child(cUID).child(date).set(pUID); 
}); 

私はpush()。getKey()を使ってクライアント側でそれを行うことができ、プロバイダーがclientAppsノードに書き込むことを許可していますが、それはそれほどエレガントではないようです。

クラウド機能でこれを行う方法はありますか?

there are provider and their clients who make appointments

乾杯

答えて

3
代わりの予定のリストの新規作成された任命であるためにあなたのトリガーの場所を変更

:実例として

、私のデータ構造は次のようになります。そして、あなたが直接任命データにアクセスすることができます

exports.storeNewAppForClient = functions.database.ref("/providerApps/{UID}/{pushId}").onWrite(event => { 
     // Exit when the data is deleted. 
     if (!event.data.exists()) { 
     console.log("deletion -> exiting"); 
     return; 
     } 

     const pUID = event.params.UID; 
     const params = event.params; 
     console.log("params: ", params); 

     const date = event.data.child('dateStr').val(); 
     const cUID = event.data.child('clientUID').val(); 

    return admin.database().ref('clientApps').child(cUID).child(date).set(pUID); 
}); 

(フランクさんのコメントに更新)

+1

[Firebaseのドキュメント](https://firebase.google.com/docs/functions/database-events#handle_event_data )handilyはそのパラメータ 'pushId'を呼び出します。 :-) –

+0

Yepp、私は完全に{pushId}逃した。 ありがとうございました! – ezmegy

関連する問題