kelliehughesspare kelliehughesspare - 7 months ago 19
HTML Question

Update in Firebase deleting other entries

I am trying to enter a number of shifts under their date. This is working fine for the 19-01 but then when I try to enter the 20-01 that saves and deletes the entry of the 19-01.

Anyone know what the problem is and why it can't allow me to have more that one tree?

//ROSTERS SAVING
//ROSTERS FOR MONDAYS
$(function Monday(){

// CREATE A REFERENCE TO FIREBASE
var dateMondayRef = new Firebase('https://shiftsapp.firebaseio.com/roster');

// REGISTER DOM ELEMENTS
var date1Field = $('#date1Input');
var emp1put1Field = $('#emp1Input1');
var enter1Field = $('#enter1');

// LISTEN FOR KEYPRESS EVENT
enter1Field.keypress(function (e) {
if (e.keyCode == 13) {
//FIELD VALUES
var dateMonday = date1Field.val();
var emp1put1 = emp1put1Field.val();
var enter1 = enter1Field.val();

//SAVE DATA TO FIREBASE AND EMPTY FIELD
var obj1 = {};
obj1[dateMonday] = {
emp1:emp1put1,
}

dateMondayRef.set(obj1);
enter1Field.val('');
}
});

});

$(function Tuesday(){

// CREATE A REFERENCE TO FIREBASE
var dateTuesdayRef = new Firebase('https://shiftsapp.firebaseio.com/roster');

// REGISTER DOM ELEMENTS
var date2Field = $('#date2Input');
var emp1put2Field = $('#emp1Input2');
var enter2Field = $('#enter2');

// LISTEN FOR KEYPRESS EVENT
enter2Field.keypress(function (e) {
if (e.keyCode == 13) {
//FIELD VALUES
var dateTuesday = date2Field.val();
var emp1put2 = emp1put2Field.val();
var enter2 = enter2Field.val();

//SAVE DATA TO FIREBASE AND EMPTY FIELD
var obj = {};
obj[dateTuesday] = {
emp1:emp1put2
}

dateTuesdayRef.set(obj);
enter2Field.val('');
}
});

});

Answer

This happens because you use Firebase's set method instead of update on the same ref (your dateMondayRef and dateTuesdayRef both point to the same Firebase node).

As described in the docs, set will

write or replace data

In other words, when you call set on your ref, you instruct firebase to write at this location (or replace any data that might be stored there with) the object you pass as an argument.

You can either use update on this ref (but that would preserve any child key that was present at roster/$dateMonday but that is not included in your new object) or grab a reference to your dateMonday node, and call set on that.

dateMondayRef.update(obj1)
dateTuesdayRef.update(obj2)
// or
dateMondayRef.child(dateMonday).set({emp1: ...})
dateTuesdayRef.child(dateTuesday).set({emp1: ...})