Firebase data gets overwritten ! sought guidance

时间:2015-07-08 15:38:35

标签: javascript firebase angularfire

I am building an Angular App with Firebase.

My intention is to create an object (say Rooms) at the root with 3 child objects (say Room1, Room2 & Room3) . Also, I am trying to create a logic that would check if the Rooms object is there - it wont create it again.

My code was :

var ref = new Firebase(firebaseURL);
ref.child('Rooms').once('value', function (snapshot){
  if(snapshot.numChildren() == 0){
    // Create Room within a loop
    ref.child('Rooms').child(i).set(roomObj);
  }else if(snapshot.numChildren() > 0){
    // do not create
  }
}

But when the code runs - it always enters into the if block !! And creates the child Rooms.

What is my mistake in the code ??

1 个答案:

答案 0 :(得分:0)

很可能会使用您期望的值再次触发值事件。

您的解决方案是在事务中运行代码。

var ref = new Firebase(firebaseURL);
ref.child('Rooms').transaction(function (data){
  if(!data){
    var rooms = {};
    for (var roomNum=0; roomNum < 3; roomNum++) {
      rooms['room'+roomNum] = { name: 'Room '+roomNum };
    }
    return rooms
  }
}

因此,如果房间尚未存在,则上述代码会创建它们。如果它们已经存在,则代码不执行任何操作(不返回值,不保留数据)。

请务必阅读Firebase documentation for transaction