Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How to merge duplicate Firestore documents?

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!