简体   繁体   中英

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?

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(),
        });
    }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM