📅  最后修改于: 2023-12-03 14:41:12.291000             🧑  作者: Mango
set()
vs update()
Firebase provides two methods, set()
and update()
, for modifying data in the real-time database or Cloud Firestore. Understanding the differences between these methods is crucial for developers working with Firebase.
set()
The set()
method is used to completely overwrite the data at a specified location. It replaces the existing data with the new data provided. If the location does not exist, it creates a new one.
firebase.database().ref('path/to/data').set({ key1: value1, key2: value2 });
or
firebase.firestore().doc('path/to/document').set({ key1: value1, key2: value2 });
set()
when you want to replace the entire data at a particular location.// Real-time Database example
firebase.database().ref('users/user1').set({
name: 'John',
age: 25,
});
// Cloud Firestore example
firebase.firestore().doc('users/user1').set({
name: 'John',
age: 25,
});
update()
The update()
method is used to modify specific fields of data at a specified location. It allows for partial updates and merges the new data with the existing data at that location.
firebase.database().ref('path/to/data').update({ key1: value1, key2: value2 });
or
firebase.firestore().doc('path/to/document').update({ key1: value1, key2: value2 });
update()
when you want to modify specific fields within the data at a particular location without overwriting the entire data.// Real-time Database example
firebase.database().ref('users/user1').update({
age: 26,
});
// Cloud Firestore example
firebase.firestore().doc('users/user1').update({
age: 26,
});
In summary, set()
is used to completely replace the data at a specified location, while update()
is used to modify specific fields within the existing data without overwriting the entire data.
Consider your requirements carefully when choosing between these methods. If you only need to update specific fields, update()
is the recommended approach. If you want to replace all the data or create a new document completely, use set()
.
Remember to import the necessary Firebase libraries to use these methods.