MongoDB 数据库指南

Finch 使用 mongo_dart 包进行 MongoDB 数据库操作。您可以使用 mongo_dart 包在 Finch 应用程序中执行数据库操作。

连接到 MongoDB 数据库

要连接到 MongoDB 数据库,您需要将以下代码添加到 app.dart 文件中。

import 'package:finch/finch.dart';

void main() async {
  final configs = FinchConfigs(
    dbConfig: FinchDBConfig(
      enable: true,
      host: 'localhost',
      port: '27017',
      user: 'database_username',
      pass: 'database_password',
      dbName: 'database_name',
    ),
  );

  final server = FinchApp(configs: configs);

  server.start().then((value) {
    Console.p("Server started: http://localhost:${value.port}");
  });
}

在上面的示例中,我们启用了 MongoDB 数据库并指定了主机、端口、用户名、密码和数据库名称。您可以更改这些值以匹配您的数据库配置。

使用 MongoDB 数据库

要使用 MongoDB 数据库,可以使用 app.mongoDb 属性。此属性返回 Db 对象,您可以使用它来执行数据库操作。

var db = app.mongoDb;

数据库集合

Finch 提供了一种简单的方法来为 MongoDB 数据库创建数据库集合。您可以使用 DBCollection 类来定义数据库集合的结构。DBCollection 类提供了一种简单的方法来定义集合的字段。您可以使用 DBField 类来定义集合的字段。

import 'package:finch/finch.dart';

class ExampleCollection extends DBCollection {
  ExampleCollection() : super(db: app.mongoDb, name: 'example');

  Future<void> insertExample(ExampleModel model) async {
    await collection.insert(model.toJson());
  }

  Future<List<ExampleModel>> getAllExample({
    int? start,
    int? count,
  }) async {
    start = (start != null && start > 0) ? start : null;
    var rows = await collection
        .modernFind(
          limit: count,
          skip: start,
          sort: DQ.order('_id'),
        )
        .toList();
    return ExampleModel.fromListJson(rows);
  }
}

在上面的示例中,我们定义了一个名为 example 的集合,包含两个字段:titleslugtitle 字段定义为字符串并设置为主键。slug 字段定义为字符串。

您可以使用 DBCollection 类为应用程序创建集合。您还可以使用 DBCollection 类在集合之间创建关系。例如,您可以在两个集合之间定义外键关系。

查询数据

Finch 提供了一种简单的方法来从 MongoDB 数据库查询数据。您可以使用 modernFind 方法从集合中查询数据。modernFind 方法提供了一种简单的方法来从集合中查询数据。您可以使用 DQ 类来构建查询。

var rows = await collection
    .modernFind(
      limit: count,
      skip: start,
      sort: DQ.order('_id'),
    )
    .toList();

示例

有关更多信息,您可以查看 Finch 存储库中的 example 项目。该示例项目使用 MongoDB 数据库和 Finch 的数据库功能。