0

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 Answers2

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)
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
NoNam4
  • 786
  • 4
  • 15
1

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);
Aniket Pandey
  • 464
  • 1
  • 9
  • @HarshSingh Please don't try to write everything in one line. Separate the code whenever it get's too complex. Make it easier to read/understand and debug. – Aniket Pandey Jun 19 '23 at 18:45