Creating a document in Firestore can be done with .add()
or with .set()
. For this particular questions, let's assume that the document holds a property with its own docId.
Approach with .add()
and a following .set()
update:
db.collection("cities").add({
docId: null,
name: 'Tokyo',
country: 'Japan'
});
//... get docId of inserted document via DocumentReference Promise return of add()
//update with docId
db.collection("cities").doc(docId).set(city, {merge: true});
Approach with only using set()
:
const newCityRef = db.collection('cities').doc();
// Later...
const res = await newCityRef.set({
// ...
});
Is there any particular advantage of using .add()
when I want to store a document that holds its own docId? Also, is there any particular disadvantage to always creating new documents with .set()
?
When using the second approach, does .doc()
always return an ID that's unique and unused? Using the first approach would always result in two write operations, while only using .set()
requires only one.