假设我有一个“用户”集合,并且很高兴他们的 ID 是生成的 Firestore documentId,如下所示:
Users Collection
GENERATED_FIRESTORE_ID1:
name: "User 1 name"
...: etc.
GENERATED_FIRESTORE_ID2:
name: "User 2 name"
...: etc."
我正在添加它们,并使用自定义对象检索它们(我目前正在使用 Android,但我想这个问题更普遍)。我不想在文档中有额外的“id”字段,只需使用document.getId()
方法来获取生成的firestore ID。
是否有正确的方法将 POJO 映射为没有单独的 ID 字段,但在查询时将其设置为应用程序使用?我使用 @Exclude 注释来执行此操作,如下所示:
public class User {
// as a side question, do I need @exclude on the field or just the getter?
@Exclude
String uId;
String name;
String email;
//... additional fields as normal
public User() {
}
@Exclude
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.displayName = name;
}
//... etc. etc.
}
然后我创建 User 对象并设置其 ID,如下所示:
for (DocumentSnapshot doc : documentSnapshots) {
User user = doc.toObject(User.class);
user.setId(doc.getId());
users.add(user );
}
这工作得很好,如果这确实是这样的话,我很抱歉,但我是 FireStore 的新手(我很喜欢它)并且想确保我做得正确。我只是想知道是否有一种方法这一切都是自动的,无需@Exclude,然后在之后手动设置IDdoc.toObject(MyCustomObject.class)
现在有一个注释 -
你可以简单地使用
@DocumentId
String uID
https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentId.html https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentId.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)