skip to Main Content

I want to structure a collection such that "mainCollection" => "Client" => "Location" => { …data } . Client and Location have Client name and Location as IDs . I wanted to add data in this collection , and used

const docRef = await addDoc(
        collection(db, "mainCollection", "Client","Location"),
        {
            ...data
        }
    );
console.log(docRef.id);

which generated an id , I want to do it in such a way that id remains Location name

Results I got – Image1
Image2

2

Answers


  1. You can set data into location doc ID as following:

    firestore.doc(`/mainCollection/${clientDocID}/${locationColId}/${locationDocID}`).set({
      ... your data
    }, {
     merge: true // you can remove these brackets if you don't need merge
    })
    

    Or if you want dynamic IDs:

    const docRef = firestore.collection(`/mainCollection/${clientDocID}/${locationColId}/`).add({
      ... your data
    })
    
    console.log('Added document with ID: ', docRef.id)
    
    Login or Signup to reply.
  2. use setDoc with the document id already included in the docRef. One thing to keep in mind that setDoc will override the doc if already exist. While, addDoc auto assigns the document id.

     const location="California";
     const docRef =doc(db, "mainCollection", "Client", "Location", location);
     await setDoc(docRef, { ...data});
     console.log(docRef.id);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search