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.
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()?
I believe that you've already answered this part of your question with the following valid assessment you issued:
Using the first approach would always result in two write operations, while only using .set() requires only one.
Meaning that billing-wise the more writes you issue the more you'd be billed as you are billed depending on the location of the instance by the number of writes per 100,000 documents. Now, implementation-wise the following section of the docs reveals that there are no particular differences of the methods themselves behind the scenes:
Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.
So I believe that for your particular use case using the doc() set()
approach could be the best approach (to avoid an increased in billing due to the number of writes).
When using the second approach, does .doc() always return an ID that's unique and unused?
Using .doc() will necessarily create an empty document with an automatically generated identifier that is unique as advised on the reference for the doc() method.