firebase / firebase/firebase-tools

[Firestore emulator] `setDoc` issues a `CREATE` request but also a `UPDATE` request at the same time

Open
#6,719 6 comments 1 reaction 0 assignees View on GitHub
emulators: firestore type: bug
Dominant language
TypeScript
Stars
4.5k
Forks
1.3k
Avg merge
1d 12h
Merged PRs (30d)
84

Description

### [REQUIRED] Environment info

**firebase-tools:**13.1.0

**Platform:**Windows 10 Pro 22H2

### [REQUIRED] Test case

Create a document using `addDoc()`, for example with:
```typescript
const data = { id: 'some_id', name: 'name' }
const commentRef = await addDoc(collection(testFirestore, 'comments'), data)
```

Then create a document using `setDoc()`, for example with:
```typescript
const commentRef = doc(collection(testFirestore, 'comments'), 'DBG')
const data = { id: commentRef.id, name: 'name' }
await setDoc(commentRef, data)
```

### [REQUIRED] Steps to reproduce
Do the above to create a doc with `setDoc()` and one with `addDoc()`

### [REQUIRED] Expected behavior

One `CREATE` request issued for both.

### [REQUIRED] Actual behavior

When creating a document with `setDoc()` : 2 requests are issued: one `CREATE` and one `UPDATE`. The `UPDATE` one seems totally useless.
The problem does not appear with `addDoc()`: only a `CREATE` request is performed.

This issue was in fact [already reported on the Firebase SDK](https://github.com/firebase/firebase-js-sdk/issues/7739). It was closed because not in the right repo, but I did not find it in this repo.

This issue is really blocking because I want to create some security rules to allow the creation of a document only if it does not exist. The `CREATE` request is correctly denied but the `UPDATE` request is not, resulting in the document being overwritten (which is exactly why I wanted to avoid...). Here is my `firestore.rules` files:
```
rules_version = '2';

service cloud.firestore {
match /databases/{database}/documents {
match /comments/{document} {
allow create: if false;
allow update: if true;
}
}
}
```
_(Note: I cannot deny all updates on this collection, as I want to allow them also in some cases. What I want is to enforce that creation is not performed if the document already exists.)_

And here is what I have in the `Requests` tab of the emulator:
![image](https://github.com/firebase/firebase-tools/assets/3687098/dc82a109-b287-4480-b763-6bca524a9778)
![image](https://github.com/firebase/firebase-tools/assets/3687098/6e33b226-0bbc-45ab-8f20-07b1101e83f2)
![image](https://github.com/firebase/firebase-tools/assets/3687098/9fdd3e96-f52b-4efc-a4e4-85c950a81344)
In fact I even have a third request, another `UPDATE` similar to the previous one:
![image](https://github.com/firebase/firebase-tools/assets/3687098/4c22d54a-2a0f-4de8-b316-a243026d8fff)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.