中心的な質問を理解すれば、短い答えは、空の配列を Firebase に強制する方法はないということだと思います。ただし、上記のパラダイムよりもうまく機能するパラダイムがいくつかあります。
Firebase はリアルタイム環境であることに注意してください。車と事故の数は、いつでも変化する可能性があります。すべてをリアルタイムで到着する新しいデータとして扱い、存在するか存在しないかについて考えることさえ避けるのが最善です。
// fetch all the people in real-time
rootRef.child('people').on('child_added', function(personSnapshot) {
// monitor their cars
personSnapshot.ref().child('cars', 'child_added', function(carSnapshot) {
// monitor accidents
carSnapshot.ref().child('accidents', 'child_added', function(accidentSnapshot) {
// here is where you invoke your code related to accidents
});
});
});
if exists/unless
型ロジックが必要ないことに注意してください。特定の子のリスニングを停止するために on を監視child_removed
しcars
たりpeople
、呼び出したりすることもあることに注意してください。ref.off()
何らかの理由で静的モデルに固執したい場合は、forEachが友達になります。
// fetch all the people as one object, asynchronously
// this won't work well with many thousands of records
rootRef.child('people').once('value', function(everyoneSnap) {
// get each user (this is synchronous!)
everyoneSnap.forEach(function(personSnap) {
// get all cars (this is asynchronous)
personSnap.ref().child('cars').once('value', function(allCars) {
// iterate cars (this is synchronous)
allCars.forEach(function(carSnap) { /* and so on */ });
});
});
});
forEach を使用しても、「存在するかしないか」のようなロジックは必要ないことに注意してください。