Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Function Increment counter without reading document

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 ?

like image 834
Mozes Ong Avatar asked Apr 01 '19 02:04

Mozes Ong


1 Answers

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

like image 185
Frank van Puffelen Avatar answered Oct 18 '22 22:10

Frank van Puffelen