Reputation: 19
I need to decrement some values of product's count when user orders, I use updateDoc() in loop but it throws
Error: Expected type 'af', but it was: a custom fg object
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
let docs = [doc(db, "myCollection", 'a'), doc(db, "myCollection", 'b')];
async function test() {
for (let i = 0; i < 2; i++) {
let doc = await getDoc(docs[i]);
console.log(doc.data());
await updateDoc(doc, {
num: increment(-1)
})
}
}
test();
Upvotes: 0
Views: 117
Reputation: 50920
The updateDoc()
function takes a DocumentReference
as the first parameter and not a DocumentSnapshot
. Also you don't have to fetch the document before updating in this case. Try:
let docs = [doc(db, "myCollection", 'a'), doc(db, "myCollection", 'b')];
async function test() {
for (let i = 0; i < 2; i++) {
// doc in original code is a DocumentSnapshot
// docs[i] is a DocumentReference
await updateDoc(docs[i], {
num: increment(-1)
})
}
}
You can use Promise.all()
to run all the promises simultaneously as shown below:
let docs = ["a", "b"];
async function test() {
const promises = docs.map((d) => {
return updateDoc(doc(db, "myCollection", "b"), {
num: increment(-1)
})
})
await Promise.all(promises)
}
If you want to ensure that all updates are successful or none, then also checkout Batched Writes.
Upvotes: 3