gpt4 book ai didi

java - Firestore SetOptions.mergeFields 不存储字段

转载 作者:行者123 更新时间:2023-12-02 10:38:01 26 4
gpt4 key购买 nike

所以我有这个函数可以在用户成功注册后将用户存储到Firestore中。

//User class
id: String
email: String?
displayName: String?
photoUrl: String?

//updateOrInsertUser method
collectionReference.document(user.id)
.set(
user,
SetOptions.mergeFields(
FIELD_photoUrl,
FIELD_email,
FIELD_displayName
)
)

但是当我调用 updateOrInsertUser(user) 时,只有 SetOptions 中的字段会存储在 Firestore 中,因此 id 不会存储。

如果文档已经存在并且没有文档存储所有内容,是否有一种简单的方法来覆盖在 SetOptions 中定义的旧值?我不想在更新之前获取旧文档:(

不,我不想将 id 添加到 SetOptions 中(想象一下当您不想覆盖数据库中已存在的字段时的其他用例)

最佳答案

But when I call updateOrInsertUser(user) only fields that are in SetOptions are stored in firestore, therefore id is not stored.

这是正常行为,因为您没有将 id 传递给 SetOptions 的 mergeFields() 方法。

Is there a simple way to override old values defined in SetOptions if the document already exists and if there is not doc store everything? I don't want to fetch old document before updating :(

最简单的方法是获取“旧”文档,更改其值并将其写回数据库,但还有另一种方法可以帮助您更改文档中的值,这是通过使用 Map 以及 update() 方法调用。在代码中,可能如下所示:

Map<String, Object> user = new HashMap<>();
user.put("photoUrl", FIELD_photoUrl);
user.put("email", FIELD_email);
user.put("displayName", FIELD_displayName);
userDocumentReference.update(user);

关于java - Firestore SetOptions.mergeFields 不存储字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com