Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase create or update in Cloud Firestore

i'm developing a simple app and a have a single doubt about Firebase Cloud Firestore.

When we do db.doc('docname').set(myInfo) in code, does Firebase consider it as a Create or a Update ?

like image 690
Pedro Saraiva Avatar asked Oct 24 '18 09:10

Pedro Saraiva


People also ask

What is onSnapshot Firebase?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

How does firestore create data?

For sending data to the Firebase Firestore database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app's package name > Right-click on it and click on New > Java Class > Give a name to your class.


2 Answers

If you are simply using the set() function, it means that if the document does not exist, it will be created. This means that you'll be billed for a write operation. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:

var setWithMerge = yourDocRef.set({
  yourProperty: "NewValue"
}, { merge: true });

This will also represent a write operation and you'll also be billed accordingly. If you are want to update a property as in the following code:

return yourDocRef.update({
    yourProperty: "NewValue"
})
.then(function() {
    console.log("Document successfully updated!");
})
.catch(function(error) {
    console.error("Error updating document: ", error);
});

It also means that you are performing a write operation. According to the official documentation regarding Firestore usage and limits, there is no difference between a write operation and a update operation, both are considered write operations.

like image 84
Alex Mamo Avatar answered Oct 16 '22 04:10

Alex Mamo


Set is equal to creating a new Document:

// Add a new document in collection "cities"
db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

Will create you a new Document named LA with the properties below. Or if you dont want to specify a ID and want Firestore to set a Auto Unique ID for you:

db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})

Update has its own function in Firestore:

// To update age and favorite color:
db.collection("users").doc("frank").update({
    "age": 13,
    "favorites.color": "Red"
})

More examples and explanation

like image 21
Badgy Avatar answered Oct 16 '22 03:10

Badgy