Firestore - 如何保存数据?

Firestore - How to save data?

这听起来可能很愚蠢,但我很困惑。您应该如何将数据保存到 Firestore?

是否应该在添加和检索之前转换to/from json?或者它应该保存为地图,如:

({'sugars': sugars, 'name': name, 'strength': strength})

实时数据库有什么不同吗?

我看到有人在他们的模型中添加了以下内容类:

      final FieldModel field;
  final int number;
  final String id;

  TransactionModel({
    required this.field,
    required this.number,
    this.id = '',
  });


  /// this conversion to json
  factory TransactionModel.fromJson(String id, Map<String, dynamic> json) =>
      TransactionModel(
        field: FieldModel.fromJson(json['field']['id'], json['field']),
        id: id,
        number: json['number'],
      );

我的问题是:为什么他们将其转换为 json?总是需要吗?这是用于 Firestore 还是实时数据库?

您可以找到有关在 Cloud Firestore 中获取和存储数据的所有详细信息 here

Firestore stores data within "documents", which are contained within "collections". Documents can also contain nested collections. For example, our users would each have their own "document" stored inside the "Users" collection. The collection method allows us to reference a collection within our code.

要向 Firestore 添加条目,您需要将 Map<String, dynamic> 传递给 collectionadd() 函数或 set() 函数文档.

您可以像这样发送数据。

await FirebaseFirestore.instance.collection('users').add({
    'full_name': fullName, // John Doe
    'company': company, // Stokes and Sons
    'age': age // 42
  });

或者,您也可以这样做:

await FirebaseFirestore.instance.collection('users').add(
    userModel.toJson(),
  );

其中,toJson()

Map<String, dynamic> toJson() => {
  "full_name": fullName,
  "company": company,
  "age": age,
};

To read a collection or document once, call the Query.get or DocumentReference.get methods.

class GetUserName extends StatelessWidget {
  final String documentId;

  GetUserName(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data =
              snapshot.data!.data() as Map<String, dynamic>;
          return Text("Full Name: ${data['full_name']} ${data['last_name']}");
        }

        return Text("loading");
      },
    );
  }
}

关于回答你的问题:

My question is: Why do they convert it to json? Is it always required? Is this for Firestore or Realtime Database?

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built-in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

JSON.

可参考this回答

总而言之,JSON 或地图用于数据传输,因为它以 well-structured 方式(key-value 对)提供数据。与 CSV 等其他数据传输格式相比,它更易于阅读。

有几种方法可以将数据写入 Firestore:

  • 设置集合中文档的数据,明确指定文档标识符。
  • 将新文档添加到集合中。在这种情况下,Firestore 会自动生成文档标识符。
  • 使用自动生成的标识符创建一个空文档,稍后为其分配数据。

要创建或覆盖单个文档,请使用 set() 方法:

import { doc, setDoc } from "firebase/firestore"; 

// Add a new document in collection "cities"
await setDoc(doc(db, "cities", "LA"), {
 name: "Los Angeles",
 state: "CA",
 country: "USA"
});

如果文档不存在,将创建它。如果文档确实存在,其内容将被新提供的数据覆盖,除非您指定数据应合并到现有文档中,如下所示:

import { doc, setDoc } from "firebase/firestore"; 

const cityRef = doc(db, 'cities', 'BJ');
setDoc(cityRef, { capital: true }, { merge: true });

如果您不确定文档是否存在,请通过将新数据与任何现有文档合并的选项以避免覆盖整个文档。对于包含地图的文档,请注意使用包含空地图的字段指定集合将覆盖目标文档的地图字段。

有关详细信息,请阅读此 docs

JSON 是 JavaScript Object Notation 的缩写,是一种开放的标准格式,它是轻量级的 text-based,专为 human-readable 数据交换而设计。它是一种 language-independent 数据格式。它支持几乎所有类型的语言、框架和库。

JSON 是用于在 Web 上交换数据的开放标准。它支持对象和数组等数据结构。因此,从 JSON.

写入和读取数据很容易

在JSON中,数据以key-value对表示,花括号包含对象,每个名称后跟一个冒号。逗号用于分隔 key-value 对。方括号用于存放数组,其中每个值是comma-separated.

你可以通过这个linkJSON

最后,正如@eNeM 所说,JSON 或地图用于数据传输,因为它以 well-structured 方式(key-value 对)提供数据。与 CSV 等其他数据传输格式相比,它更易于阅读。