为什么我们向firestore发送数据时,HashMap中的参数设置为object?

Why do we set the parameter in HashMap to object when sending data to firestore?

我正在观看一个视频来创建一个简单的应用程序(只是为了练习概念),用户可以在其中输入标题和他们的想法。此数据将发送到 Firestore。

但是,我对通过 HashMap 发送数据的部分感到困惑:

Map<String, Object> data = new HashMap<>();
data.put(STRING_TITLE, title);
data.put(STRING_THOUGHTS, thoughts);

标题和想法基本上就是用户输入的标题和想法的字符串值。

String thoughts = edtThoughts.getText().toString().trim();
String title = edtTitle.getText().toString().trim();

在那之后,我所做的就是将它传递到 journalRef:journalRef.set(data) 其中 journalRef 只是我数据库的 DocumentReference:

private FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference journalRef = db.collection("Journal").document("MyThoughts");

我的问题是:为什么我们将数据传递为 Map<String, Object> 而不是 Map<String, String>。标题和想法不就是用户输入的字符串值吗?

编辑:

此外,当我转到 Firestore 时,为什么它会将想法和标题显示为字符串而不是 Object(在 HashMap 中声明)?

谢谢!

您可以将上述示例声明为 Map<String, String>,因为您放入其中的数据很简单。但更高级的示例可能会让您将更深层次的结构化对象放入 Firestore,因此使用 Map<String, Object> 更合适。 Firestore 是一个“文档存储数据库”,其中文档是一个 HashMap。该散列中的元素是 name/value 对,其中名称是字符串,值可以是:字符串、布尔值、数字、时间戳、数组、(Hash)Map、地理位置。

所以将 data 声明为 HashMap<String, Object> 更正确,因为 可以 进入其中。

在 Firestore 文档中,字段名称始终是精确的字符串,而值是 object。如果要添加字符串、布尔值、数字或任何类型的 object 即 supported data type,都可以视为 object 并不重要。 Java 中的第一条规则是一切都是 object。所以无论你向数据库中添加什么,Firestore 都会始终根据其数据类型保存数据。回答你的问题:

Why do we pass data as Map<String, Object> instead of Map<String, String>?

您需要根据您需要执行的操作来传递数据。如果要使用 set() method, then you can use Map<String, String> and this is because this method requires an argument of type Object. However, if you want to perform an update operation using the update() method, please note that you cannot use Map<String, String>, because the method requires a Map<String, Object>. Besides that, when you want to perform an update, you can pass different types of objects as values, and get the fields updated accordingly. So you can always update multiple fields at once.

向数据库添加数据

Isn't the title and thoughts just the user's input as a String value?

是的,是的。如果你只想使用set()添加标题和想法,那么你可以使用Map,否则,对于更新操作,你需要使用Map.

并回答您编辑过的问题:

Also, when I go to Firestore, why does it show the thoughts and title as a String rather than an Object(which was declared in the HashMap)?

它将始终根据您添加的值显示值。在 Firebase 控制台中,没有 object 除了地图的表示。除此之外,在幕后,您添加的每个 object 都有一个 instanceof 验证。因此,如果您传递一个字符串,那么 Object 将始终保存为一个字符串,而不是以任何其他方式保存。