Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent Firebase set() from overwriting existing data?

Tags:

firebase

If I do this, all is good with my itemRef:

itemRef.child('appreciates').set(newFlag);
itemRef.child('id').set(newId);

other properties of itemRef remain BUT child_changed is called twice

If I do this:

itemRef.set({appreciates:newFlag,id:newId});

child_changed is called only once but my other properties are destroyed. Is there a workaround besides the clumsy one of repopulating the entire reference object?

Thanks,

Tim

like image 886
Itumac Avatar asked Oct 02 '12 05:10

Itumac


People also ask

What does the set () method in the Firebase library do?

Learn more about the tree-shakeable Web v9 modular SDK and upgrade from version 8. Using set() overwrites data at the specified location, including any child nodes.

How do you overwrite in Firebase?

push() , you can use . update() (or . set() when you have child) for updating information.

What are the restrictions in Firebase?

Firebase Security Rules work by matching a pattern against database paths, and then applying custom conditions to allow access to data at those paths. All Rules across Firebase products have a path-matching component and a conditional statement allowing read or write access.

Does Firebase own your data?

You don't own your data Plus, it was not possible to export our data when we had hundreds megabytes hosted. We had to contact Firebase by email. Notice: exporting data email/password data is possible by contacting Firebase Team, but not from Dashboard.


2 Answers

Now .update takes care of it, you can change existing data or add new one without affecting the rest of data you already had there.

In this example, I use this function to set a product as sold, the product has other variables with data and may or may not have sold or sellingTime but it doesn't matter cos if it doesn't exist will create them and if it does, will update the data

var sellingProduct = function(id){
 dataBase.ref('product/'+id).update({
   sold:true,
   sellingTime: Date.now(),

 }).then (function(){
   alert ('your product is flaged as sold')

 }).catch(function(error){
    alert ('problem while flaging to sold '+ error)
 })

}
like image 173
RamiroIsBack Avatar answered Oct 05 '22 14:10

RamiroIsBack


Though you can use update, you can also use set with merge option set to true:

itemRef.set({ appreciates:newFlag, id:newId }, { merge: true });

This will create a new document if it doesn't exists and update the existing if it does.

like image 42
Dharmaraj Avatar answered Oct 05 '22 13:10

Dharmaraj