Reputation: 1159
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?
Upvotes: 3
Views: 1150
Reputation: 599716
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.
Upvotes: 1
Reputation: 4770
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(),
});
}
});
Upvotes: 2