How to increment a data field in Firestore using Firebase Modular SDK V9?

So I’m trying to increment data for sending a num to other user’s num.

const sendNum = async(e) => {
        e.preventDefault();
        
        
        const targetQuery = query(userCol, where("keycode", "==", parseInt(target)));
        const targetSnapshot = await getDocs(targetQuery)
        
        targetSnapshot.forEach((document) => {
            console.log(document.data().num)
            console.log(document.id)
            const targetRef = doc(db, 'users', document.id)

            setDoc(targetRef, {
                num: // increment user data here
            }, {merge: true})
        })
}

But a documentation that I found, I don’t really understand them. And the one I understand, it’s already outdated. So I would be very happy if anyone know how 🙂

Answer

The documentation has a dedicated section for that called increment a numeric value.

import { setDoc, increment } from "firebase/firestore";

await setDoc(targetRef, {
    num: increment(50)
});

You cannot use await in a forEach loop (setDoc returns a promise and must be awaited) so try using either Batch Writes or Promise.all().

Using async/await with a forEach loop