在Firestore中为文档ID的自定义对象建模的最佳方法是什么? [英] What's the best way to model Custom Object for Document ID in Firestore?
问题描述
说我有一个用户"集合,很高兴他们的ID可以是生成的Firestore documentId,例如:
Say I have a collection of 'Users', and am happy for their ID to be the generated Firestore documentId, something like:
Users Collection
GENERATED_FIRESTORE_ID1:
name: "User 1 name"
...: etc.
GENERATED_FIRESTORE_ID2:
name: "User 2 name"
...: etc."
,我正在添加它们,并使用自定义对象来检索它们(目前我正在使用Android,但我想这个问题更笼统).我不想在文档中有多余的"id"字段,只需使用document.getId()
方法即可获取生成的Firestore ID.
and I am adding them, and retrieving them with a custom object (I'm using Android at the moment but the question I guess is more generalistic). I don't want to have an extra "id" field in the document, just use the document.getId()
method to get the generated firestore ID.
是否存在将POJO映射为不具有单个ID字段的正确方法,但是在查询时将其设置为用于应用程序使用?我正在使用@Exclude注释执行此操作,如下所示:
Is there a correct way to map a POJO to not have an indivual ID field, but when querying set it for application usage? I am doing it using the @Exclude annotation as follows:
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:
and then I create the User object and set its ID as follows:
for (DocumentSnapshot doc : documentSnapshots) {
User user = doc.toObject(User.class);
user.setId(doc.getId());
users.add(user );
}
这很好用,如果确实是这样的话,我深表歉意,但是我是FireStore的新手(我很喜欢它),并希望确保我做得对.我只是想知道是否有一种方法可以自动完成所有工作,而无需@Exclude,然后在doc.toObject(MyCustomObject.class)
This works fine, and apologies if this is indeed the way, but I'm new to FireStore (am loving it) and want to make sure I'm doing it right. I just wondered if there was a way this would all be automatic, without @Exclude and then manually setting the ID after doc.toObject(MyCustomObject.class)
推荐答案
现在有一个注释-
您可以简单地使用
@DocumentId
String uID
@DocumentId
String uID
https://firebase.google. com/docs/reference/android/com/google/firebase/firestore/DocumentId.html
这篇关于在Firestore中为文档ID的自定义对象建模的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!