2013-03-14 83 views
12

person可以有多個cars,car可以有多個accidents。所以我們可以有:如何處理Firebase中的空數組?

# Person with no cars 
person: 
    name: "Misha" 
    cars: [] 

# Person with free-accident car 
person: 
    name "Arlen" 
    cars: 
    0: 
     name: "Toyota" 
     accidents: [] 

火力地堡將這些人作爲:

person: 
    name: "Misha" 

person: 
    name "Arlen" 
    cars: 
    0: 
     name: "Toyota" 

所以在JavaScript中我必須做以下恢復空數組:(CoffeeScript的)

if person.cars? 
    for car in person.cars 
    car.accidents = [] unless car.accidents? 
else 
    person.cars = [] 

有沒有更好的方法來處理Firebase中的空數組而無需編寫這個不必要的JavaScript代碼?

回答

13

我認爲,如果我理解了核心問題,簡短的回答是,沒有辦法強制將空數組插入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類型的邏輯。請注意,您可能還需要在carspeople上監聽child_removed,並撥打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,沒有必要對「存在,或除非」之類的邏輯。

+0

大答案加藤! – 2013-03-14 16:46:49

4

我通常使用DataSnapshot功能numChildren的(),看看它是否是空的不是,這樣

var fire = new Firebase("https://example.firebaseio.com/"); 
fire.once('value', function(data){if (data.numChildren() > 0){ /*Do something*/ });