说person可以有多个cars,并且car可以有多个accidents.所以我们可以:
# Person with no cars
person:
name: "Misha"
cars: []
# Person with free-accident car
person:
name "Arlen"
cars:
0:
name: "Toyota"
accidents: []
Run Code Online (Sandbox Code Playgroud)
Firebase将这些人存储为:
person:
name: "Misha"
Run Code Online (Sandbox Code Playgroud)
和
person:
name "Arlen"
cars:
0:
name: "Toyota"
Run Code Online (Sandbox Code Playgroud)
所以在JavaScript中我必须执行以下操作来恢复空数组:(CoffeeScript)
if person.cars?
for car in person.cars
car.accidents = [] unless car.accidents?
else
person.cars = []
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来处理Firebase中的空数组,而无需编写这些不必要的JavaScript代码?
Kat*_*ato 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
});
});
});
Run Code Online (Sandbox Code Playgroud)
注意如何不需要if exists/unless类型逻辑.请注意,你可能也想监视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 */ });
});
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,即使使用forEach,也不需要"存在或除非"的逻辑.