2013-03-14 84 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*/ });