DEV Community

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

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 = {
  carName:"BMW",
  color:"red",
  parts:{
    engine:{
    brand:"BMW",
    type:"alloy"
  },
  tyre:"MRF",
  visits:0,
}

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({
    color:"white"
})

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({
    [`parts.tyre`]:"Apollo"
});

//For updating nested object with dynamic key

const dynamicValue = "tyre";
db.collection("collection name").doc("document name").update({
    [`parts.${dynamicValue}`]:"Apollo"
});

// 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({
    [`parts.engine.brand`]:"Apollo"
});

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 });

Conclusion

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

Oldest comments (0)