Firestore - Prevent overwriting when document already exists while creating documents with custom ID

Viewed 698
this.collection()
      .doc<MyModel>(documentId)
      .set(data);

I want to create a document with custom document ID, so cannot use add() on the collection, but set() on the document works. The problem is set() overwrites if the document exists. I want to prevent that behavior, create the document if and only if the ID already doesn't exist.

2 Answers

If you want to prevent overwriting in code, consider using update(). Update will update the document with the data you give it, but won't create it if it doesn't exist.

Alternatively you can use security rules to enforce this behavior on the server.


If you want to only allow creation of a document, and disallow updates and deletes use these rules:

service cloud.firestore {
  match /databases/{database}/documents {
    // A write rule can be divided into create, update, and delete rules
    match /cities/{city} {
      allow create: if true;
      allow update: if false;
      allow delete: if false;
    }
  }
}

If you're looking for a method that creates a doc if it does not exist and updates it if it does, take a look at this approach: Github comment

Related