[英]Firestore: Creating a document with specified UID, eventually with set(), but without updating the fields
Consider these lines: 考虑以下几行:
Map<String, Object> the_data = new HashMap<>();
the_data.put("login", "Anonymous");
the_data.put("avatar_is_defined", false);
the_data.put("amount", 0.0);
the_data.put("deleted", false);
the_data.put("can_read_user", true);
Toast.makeText(this, "Initializing your data... Please wait until the screen appears.", Toast.LENGTH_SHORT).show();
user_database_model.getReferenceToUser(signed_in_user_uid).set(the_data, SetOptions.mergeFields("")).addOnCompleteList[...]
First time the user signs-in, this set
call must be executed and all these fields must be actually set in the document whose UID is signed_in_user_uid
. 用户首次
signed_in_user_uid
,必须执行此set
调用,并且必须在UID为signed_in_user_uid
的文档中实际设置所有这些字段。
But, if the user signs-in again ( ie: the document already exists), this set
either must be ignored (not executed) (in reality it's impossible, see last paragraph), or its fields must not be updated (that's why I've unsuccessly intended by writing SetOptions.mergeFields("")
). 但是,如果用户再次登录( 即:文档已经存在),则必须忽略(不执行)此
set
(实际上是不可能的,请参阅最后一段),或者必须不更新其字段(这就是为什么我通过编写SetOptions.mergeFields("")
)未成功完成。
Is it possible to call a set
function saying "Firestore, please create this document and fill it with the provided fields if it doesn't exist ; but if it already exist, just... don't do anything"? 是否可以调用一个
set
函数,说“ Firestore,如果不存在,请创建此文档,并使用提供的字段填充它;但如果它已经存在,则...什么都不做”?
Important: due to Firestore Security Rules , I can't get()
the document to know if it exists or not. 重要说明:由于Firestore安全规则 ,我无法
get()
文档来知道它是否存在。 (in the callback I would have call set
only if it doesn't exist). (在回调中,仅当呼叫
set
不存在时,我才set
呼叫set
)。 So avoiding to call set
(not executing it) isn't possible in reality. 因此,实际上不可能避免调用
set
(不执行它)。
If you only want the user to be able to create their document once, and never update it, you can do so in security rules with: 如果您只希望用户能够一次创建他们的文档,而从不对其进行更新,则可以在安全规则中执行以下操作:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
// Applies to writes to nonexistent documents
allow create: if request.auth.uid != null;
// Reject writes to existing documents
allow update: if false;
}
}
}
If you want the client-side code to detect whether the document already exists, and create it if it doesn't, use a transaction . 如果您希望客户端代码检测文档是否已经存在,并创建文档(如果不存在),请使用transaction 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.