集合级别锁定不可用

集合级别锁定不可用

本文介绍了基于不存在的文档的Firestore交易(集合级别锁定不可用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于 SO答案,我知道firestore在事务中没有收集级别锁定.就我而言,我必须确保用户集合中的用户名字段是唯一的,然后再写入集合.为此,我编写了一个执行此操作的事务:

Based on this SO answer I came to know that firestore does not have collection level locking in a transaction.In my case, I have to ensure that the username field in users collection is unique before I write to a collection.For that, I write a transaction that does this:

  1. 对用户集合执行查询以检查是否存在用户名=某物的文档
  2. 如果确实存在,则失败并从事务中返回错误
  3. 如果它不存在,只需对我要更新/创建的userId运行写操作.

现在的问题是,如果两个客户端同时尝试运行此事务,则两者都可能会查询该集合,并且由于该集合未锁定,因此一个客户端可能会在集合中插入/更新文档,而另一个客户端则看不到该文档.

Now the issue here is that if two clients simultaneously try to run this transaction, both might query the collection and since the collection is not locked, one client might insert/update a document in collection while other won't see it.

我的假设正确吗?如果可以,那么如何处理这种情况?

Is my assumption correct? And if yes, then how to deal with such scenarios?

推荐答案

实际上,您无法尝试自动执行操作,因为无法安全地对无法识别的文档进行交易ID.这里的问题是,交易仅是安全的"交易.如果可以 get()添加或修改特定文档.由于无法使用文档中的字段值 get()文档,因此您很茫然.

What you're trying to do is actually not possible to do atomically, as it's not possible to transact safely on a document that you can't identify with an ID. The problem here is that a transaction is only "safe" if you can get() the specific document to add or modify. Since you can't get() a document using a field value in the document, you're at a loss.

如果要确保Firestore中任何内容的唯一性,则需要将该唯一性编码到文档ID本身中.在最简单的情况下,您可以使用用户名作为新集合中文档的ID.如果这样做,您的交易可以简单地按用户名 get()所需文档,检查其是否存在,如果不存在,则编写该文档.否则,交易可能会失败.

If you want to ensure uniqueness of anything in Firestore, that uniqueness will need to be coded into the document ID itself. In the simplest case, you can use the username as the ID of a document in a new collection. If you do that, your transaction can simply get() the required document by username, check to see if it exists, then write the document if it doesn't. Else, the transaction can fail.

请记住,因为Firestore中的文档ID有限制,如果您的用户名可能违反规则,则可能需要转义该用户名或对其进行编码.

Bear in mind that because there are limitations to document IDs in Firestore, you might need to escape or encode that username if your usernames could possibly violate the rules.

这篇关于基于不存在的文档的Firestore交易(集合级别锁定不可用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 13:50