I am looking to increment or decrements a number in cloud functions without reading the document.
I have a item documents, and when the document updates, it check for quantity. if the quantity is more than zero, increment the store profile item count. So say the store has 10 items available, and item doc field has been updated from 0 to 1 inventory, i will need to increment the store item count to 11.
I remember reading on firebase blog that there is a new feature that allows this. But how do we do it in cloud functions ?
You use the feature in Cloud Functions through the Admin SDK. Here is an example based on a project I'm working on.
First you import the Admin SDK:
var admin = require('firebase-admin');
And then in your Cloud Function you increment the field with something like:
var firestore = admin.firestore();
var docRef = firestore.collection('your_collection').doc('your_document');
docRef.update({ itemCount: admin.firestore.FieldValue.increment(1) })
This increments the field itemCount
by 1
.
Also see:
the blog post Incrementing Values Atomically with Cloud Firestore
the documentation on how to Add the Admin SDK to your project
the reference documentation for admin.firestore
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With