fireship-io / fireship.io

Build and ship your app faster https://fireship.io
3.5k stars 1.3k forks source link

snippets/firestore-increment-tips/ #749

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

How to Use Firestore Increment

Use the special Firestore Increment field value to increase or decrease numeric values atomically in the database.

https://fireship.io/snippets/firestore-increment-tips/

litehacker commented 2 years ago

Regargin the increment function for floating points, if didn't work well for me. There are some cases when it's not precisely incremented. Ex: 2.9999999999999 intstead of 3 or similar cases are veery often apprearing. For this I made this solution, not sure if it's the right one:

db.collection("Terminals")
      .doc(terminalID)
      .update(() => {
        const increaseBy = admin.firestore.FieldValue.increment(fee);
        const rounding = Math.round(Number(increaseBy));
        return { Budget: rounding };
      })