How to Use Increment in Firestore: Simple Guide
Use Firestore's
FieldValue.increment(number) to atomically increase or decrease a numeric field without reading it first. This ensures safe updates even when multiple users change the value at the same time.Syntax
The FieldValue.increment(number) method takes a number to add (positive or negative) to a numeric field in a Firestore document. It updates the field atomically, meaning it handles concurrent changes safely.
FieldValue.increment(number): The function to increment or decrement a field.number: The amount to add; use negative values to subtract.- Used inside
updateDoc()orsetDoc()with{ merge: true }to modify existing fields.
javascript
import { getFirestore, doc, updateDoc, FieldValue } from 'firebase/firestore'; const db = getFirestore(); const docRef = doc(db, 'collectionName', 'docId'); await updateDoc(docRef, { numericField: FieldValue.increment(1) // adds 1 to numericField });
Example
This example shows how to increase a user's score by 5 points in Firestore using FieldValue.increment. It updates the score field atomically without reading the current value.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, doc, updateDoc, FieldValue } from 'firebase/firestore'; const firebaseConfig = { // your config here }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); async function increaseScore(userId) { const userRef = doc(db, 'users', userId); await updateDoc(userRef, { score: FieldValue.increment(5) }); console.log('Score increased by 5'); } // Call the function with a user ID increaseScore('user123');
Output
Score increased by 5
Common Pitfalls
- Trying to increment a field that does not exist will create it with the increment value.
- Using
FieldValue.incrementon a non-numeric field causes an error. - Not using
updateDocorsetDocwith merge can overwrite the whole document. - For decrement, use a negative number like
FieldValue.increment(-3).
javascript
import { getFirestore, doc, updateDoc, setDoc, FieldValue } from 'firebase/firestore'; const db = getFirestore(); const docRef = doc(db, 'collectionName', 'docId'); // Wrong: overwrites entire document await setDoc(docRef, { numericField: FieldValue.increment(1) }); // Right: merges increment with existing fields await updateDoc(docRef, { numericField: FieldValue.increment(1) });
Quick Reference
- Increment:
FieldValue.increment(number) - Use in update:
updateDoc(docRef, { field: FieldValue.increment(1) }) - Decrement: Use negative number
FieldValue.increment(-1) - Creates field if missing: Yes, sets to increment value
- Errors: If field is non-numeric
Key Takeaways
Use FieldValue.increment to safely update numeric fields without reading them first.
Pass positive numbers to add and negative numbers to subtract.
Always use updateDoc or setDoc with merge to avoid overwriting documents.
Increment creates the field if it does not exist, starting at the increment value.
Avoid using increment on non-numeric fields to prevent errors.