Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent update if document already exists firestore batch

I have a program performing a batch write on firestore to a collection.

I am trying to write the document only if is doesn't exists in the collection and skip without modifying anything if it does.

the security rule is as below:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{id} {
      allow create,delete: if request.auth.uid != null;
    }
  }
} 

While testing on the test tool, it working as expected. I am only allowed to create and delete documents in this collection. However when running from the program, the batch write is able to modify the document field (stamp in this case) if is already exists.

The code is as follows:

var batch = firestore.batch();
var docRef= firestore.collection("collection").doc(data.id);

batch.set(
    docRef,{
        id: data.id,
        stamp: new Date(),
    },
);

What am I missing, or doing wrong?

like image 538
Tarounen Avatar asked Feb 28 '26 11:02

Tarounen


2 Answers

You can check if the document exists first and then write only if it doesnt

docRef.get().then(doc => {
    if (!doc.exists) {
        batch.set(docRef, {
            id: data.id,
            stamp: new Date(),
        });
    }
});
like image 58
Abito Prakash Avatar answered Mar 02 '26 00:03

Abito Prakash


From your comments it seems you're running this code in a Node.js environment using the Admin SDK. When you use the Admin SDK it accesses Firebase with elevated, administrative privileges and bypasses the security rules that you've specified.

With that knowledge it seems that the behavior you have is working as intended.

like image 28
Frank van Puffelen Avatar answered Mar 01 '26 23:03

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!