我想要在Firestore中存在相同的文档ID时防止写入。

huangapple go评论62阅读模式
英文:

I would like to prevent writing when there is the same document ID in firestoreb

问题

我想要防止在Firestore中存在相同的文档ID时进行写入。

我是Flutter的新手。
正如标题所述,当从Flutter写入Firestore时,如果存在相同的文档ID,通常会进行覆盖。

因此,我想要防止相同的文档ID被覆盖。

有没有好的方法可以做到这一点?

英文:

我想要在Firestore中存在相同的文档ID时防止写入。

I would like to prevent writing when there is the same document ID in firestoreb.

I am new to flutter.
As the title says, when writing from flutter to firestore, if the same document ID exists, it is usually overwritten.

So, I would like to prevent the same document ID from being overwritten.

Is there a good way to do this?

答案1

得分: 1

使用最直接的方法是按照以下安全规则:

match /kyousyoku/{docId} {
  allow write: if !exists(/databases/$(database)/documents/kyousyoku/$(docId))
}

这种方法的一个小缺点是,发送回客户端的错误消息不会指示写入失败是因为文档已经存在。它会返回一个通用的错误消息。

如果你想区分这个错误和安全规则返回的其他错误(例如用户未经身份验证),你可以使用事务

英文:

The most straightforward way is to use a security rule as follows:

match /kyousyoku/{docId} {
  allow write: if !exists(/databases/$(database)/documents/kyousyoku/$(docId))
}

A small drawback of this approach is the fact that the error message sent back to the client doesn't indicate that the write has failed because the document already exists. It returns a generic error message.

If you want to be able to make the distinction between this error and other errors returned by the security rules (e.g. the user is not authenticated) you can use a Transaction.

huangapple
  • 本文由 发表于 2023年2月26日 20:16:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定