I want to create Firestore documents if they don't exist - if they do exist, skip them (don't update). Here's the flow
var arrayOfRandomIds = [array of 500 random numbers];
for (var id of arrayOfRandomIds)
{
var ref = db.collection("tickets").doc(id);
batch.set(ref, {name: "My name", location: "Somewhere"}, { merge: true });
}
batch.commit();
I just want to know, would this overwrite any existing documents if they exist? I don't want anything overwritten, just skipped.
Thanks.
Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.
The firestore emulator is allowing two documents with the same ID to be added in a collection.
Cloud Firestore does not support the equivalent of SQL's update queries. You will always have to do this in two steps: Run a query with your conditions to determine the document IDs. Update the documents with individual updates, or with one or more batched writes.
Although Firestore is very affordable with little usage, costs start to increase as you begin to scale. In most cases, the cost of using Firestore at scale is more expensive than other providers.
I think you can use security rules to accomplish that. That way you won't be charged for an additional document read to see if it already exists.
service cloud.firestore {
match /databases/{database}/documents {
match /tickets/{id} {
allow create;
}
}
}
Firestore doesn't have a native "create but don't overwrite" operation. Here are the only available operations:
Instead of a batch, what you can do instead is perform a transaction that checks to see if the document exists, then creates it conditionally if it does not already exist. You will have to write that logic inside your transaction handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With