Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore create documents if they don't exist, skip if they do

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.

like image 394
Obi Avatar asked Jan 30 '20 16:01

Obi


People also ask

Does firestore Create collection if not exists?

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.

Can two documents have the same ID in firestore?

The firestore emulator is allowing two documents with the same ID to be added in a collection.

Can firestore update multiple documents matching a condition using one query?

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.

Is firestore too expensive?

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.


2 Answers

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;
    }
  }
} 
like image 114
Michal Kubizna Avatar answered Oct 04 '22 12:10

Michal Kubizna


Firestore doesn't have a native "create but don't overwrite" operation. Here are the only available operations:

  • update: only change the contents of an existing document
  • set without merge: create or overwrite
  • set with merge: create or update if exists

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.

like image 42
Doug Stevenson Avatar answered Oct 04 '22 11:10

Doug Stevenson