I want to create a function that loops through an array and creates a new document in the Firestore database with an id
and quantity
fields for each element in the array but I want the function to merge the documents if the another document with the same id already exists
I tried the following code:
useEffect(() => { !Locked && User && Uid && items && items.forEach(item=> User && db.collection("users").doc(Uid).collection("basket").add({ id : item.id, quantity : item.quantity }, {merge: true}) .then(setLocked(true)) ) }, [items, User,Locked,Uid])
but it did not work then I tried to change the .add
to .set
but it shows the following error:
TypeError: _backend_firebase__WEBPACK_IMPORTED_MODULE_7__.db.collection(...).doc(...).collection(...).set is not a function
Advertisement
Answer
You cannot call set
on a collection. You can only write to a document within that collection.
You will to first need to use a query to find the duplicate document, and then update that document.
If each item.id
has to be unique within a user’s basket
, consider using the item Id as the document ID, instead of calling add
:
User && db.collection("users").doc(Uid).collection("basket").doc(item.id).set({ id : item.id, quantity : item.quantity }, {merge: true})
This makes it much easier to update the document later, as you can write to the document based on its document/item id again, rather than needing a query.