John Carson John Carson - 7 months ago 5
Javascript Question

How do I use $save() in Firebase' Angular-Fire to Update Object Property Values

I have the code below:

var FBref = new Firebase('https://employees.firebaseio.com/');
var peopleObject = $firebaseArray(FBref);

var person = {
"name":"John",
"age":"20",
"phone":"123-123-123"
};

peopleObject.$add(person);


I use the code above to add new records of employees successfully.

I need to update the John's phone number to 111-111-111. But the code below doesn't work.

var person = {
"name":"John",
"age":"20",
"phone":"111-111-111" //New phone number
};

peopleObject.$save(person);


Someone advice

Answer

Currently you are trying to save whole object, which wouldn't work.

Retrieve old record first by getting record from db first & then update that record. Thereafter save that object using $save method.

//if update action is happening is similar session you can get unique by below code
var someRecordKey; 
peopleObject.$add(person).then(function(ref) { 
    //get record id of new person 
    someRecordKey = ref.key(); 
});

// get record by unique key
var person = peopleObject.$getRecord(someRecordKey);
// change a message and save it
item.phone = "111-111-111";
peopleObject.$save(person).then(function() {
    // data has been saved to our database
});
Comments