DEV Community

Cover image for Cloud Firestore Nesting Update & Increment (WEB)

Posted on

Cloud Firestore Nesting Update & Increment (WEB)

Firebase offers a well-structured document for database CRUD operations in several languages. However, I feel some areas still require a more detailed explanation like updating a nested document in firebase, incrementing value without sending unnecessary API calls.

How to update a nested key?

const data = {

const db = firebase.firestore();

So in case1, updating at level 1 is pretty straightforward. Only the key that needs to be updated is to be mentioned in the update part.

// Case 1:

//updating data at the first level of object
db.collection("collection name").doc("doc").update({

In Case2, in order to update the nested object, we need to concatenate the key names in the row.

//case 2:

//updating data at second level

db.collection("collection name").doc("document name").update({

//For updating nested object with dynamic key

const dynamicValue = "tyre";
db.collection("collection name").doc("document name").update({

// In order to update the keys of engine nested in parts of the data object, just need to concatenate. 

db.collection("collection name").doc("document name").update({

How to increment a key without making unnecessary API calls?

One of the most common challenges faced in firebase is correctly incrementing the value of the document or of multiple documents when the number of users is simultaneously updating data. For example, incrementing or decrementing the number of likes on-page.

Last year, Firebase came up with a new feature FieldValue.increment that has reduced the overall complexity of getting the values from the doc and updating it.

const db = firebase.firestore();
const increaseValue=firebase.firestore.FieldValue.increment(1);
//For the above example
db.collection('collection name').doc('document name');.update({ visits: increaseValue });


Hopefully, this post has helped you with a better understanding on updating the nested object and firebase increment part.

Top comments (0)