- Couchbase Lite でドキュメントを追加するためのバッチ操作の使用方法を学習する
- 一括でデータベースにドキュメントを挿入する
- JSONを使用してデータベース内のオブジェクトをシリアライズする
- Explore the Visual Studio Code plug-in for Couchbase Lite
はじめに
この学習パスのパートでは、ユーザーがログインして開発者画面にアクセスし、バッチ操作を使用してインベントリデータベースに10のサンプルプロジェクトを追加できる「Audit Inventory」デモアプリを使って作業します。この学習パスのこのステップでは、以下の基本事項を学習します:
- 一括でデータベースにドキュメントを挿入する
- JSON シリアライゼーションを使用して、データベースに格納されるオブジェクトをシリアライズする
- 文書の検証が完了しました
- Visual Studio Code の Couchbase Lite プラグインを使用して、追加されたドキュメントを確認します。
アプリの概要
デモアプリには多くの機能がありますが、このステップでは以下について説明します。
- アプリケーションにログインする
- 開発者画面へのアクセス
- [サンプルデータの読み込み]ボタンを使用する
- 追加されたプロジェクトドキュメントの数を確認する
- アプリに追加されたプロジェクトドキュメントを確認する

ご注意ください: This step assumes you completed the previous step
Include Pre-built Database. This part of the learning path will be confusing if you did not complete the previous step.
インストール
アプリのソースコードを取得する
ソースコードの複製
- If you haven’t already cloned the repo from the previous step, clone the
Learn Couchbase Lite with Dart and FlutterGitHubからのリポジトリ。.
git clone https://github.com/couchbase-examples/flutter_cbl_learning_path.git
試してみてください
- Open src folder using your favorite IDE
- プロジェクトのビルドと実行を行います。.
- アプリにログインします “demo@example.com“ そして “「P@ssw0rd12」” それぞれ、ユーザーIDとパスワードフィールド用です。.
- 表示されていることを確認してください
No Data was foundプロジェクト画面のメッセージ。.

データモデル
Couchbase Lite は JSON ドキュメントストアであるという点に注意してください。 文書 名前付きフィールドと値の論理的な集合です。値は任意の有効な JSON 型です。標準の JSON 型に加え、Couchbase Lite は 日付 そして ブロブ データ型。必須ではありませんが、推奨される慣行として、 “「documentType」” 関連するドキュメントの命名空間として機能するプロパティ。.
プロジェクト文書
このステップではコレクションを作成します。 文書 with a “「documentType」” 財産の所有者 “「プロジェクト」”. 各ドキュメントは、選択した倉庫に基づいて、チームが指定された期日までに作業を進め、完了する必要があるプロジェクトを表しています。これはまた、別のドキュメントタイプです。.
文書の例としては、以下のようなものがあります:
{
"team": "team1",
"modifiedOn": "1656804469897",
"documentType": "project",
"createdBy": "demo@example.com",
"dueDate": "2022-10-31",
"name": "Santa Clara Warehouse Audit",
"description": "Audit of warehouse stock located in Santa Clara, CA.",
"modifiedBy": "demo@example.com",
"warehouse": {
"documentType": "warehouse",
"name": "Santa Clara Warehouse",
"shippingTo": [
"AZ",
"CA",
"HI",
"NV"
],
"warehouseId": "e1839e0b-57a0-472c-b29d-8d57e256ef32",
"city": "Santa Clara",
"address1": "3250 Dr Olcott Street",
"postalCode": "95054",
"latitude": 32.3803024,
"state": "CA",
"salesTax": 0.0913,
"longitude": -121.9674197,
"yearToDateBalance": 0.0
},
"projectId": "663953ba-9e4c-4090-9e07-642c1778d467",
"createdOn": "1656804469897"
}
プロジェクトデータクラス
もしある人が “「プロジェクト」” それはデータベースから取得され、そのデータベース内でデータクラスの型として保存されます。 プロジェクト.
@JsonSerializable(explicitToJson: true)
class Project {
String projectId;
String name;
String description;
bool isComplete;
String documentType = 'project';
DateTime? dueDate;
Warehouse? warehouse;
//security tracking
String team;
String createdBy;
String modifiedBy;
DateTime? createdOn;
DateTime? modifiedOn;
Project( {
required this.projectId,
required this.name,
required this.description,
required this.isComplete,
required this.dueDate,
required this.warehouse,
required this.team,
required this.createdBy,
required this.createdOn,
required this.modifiedBy,
required this.modifiedOn});
String dueDateToString() {
var date = dueDate;
if (date != null) {
return '${date.month}/${date.day}/${date.year}';
}
return '';
}
factory Project.fromJson(Map<String, dynamic> json) =>
_$ProjectFromJson(json);
Map<String, dynamic> toJson() => _$ProjectToJson(this);
}
倉庫クラス
もしある人が “「倉庫」” プロジェクトから取得されたデータはデータベースから取り出され、データクラスの型として格納されます。 倉庫.
@JsonSerializable(explicitToJson: true)
class Warehouse {
final String warehouseId;
final String name;
final String address1;
final String? address2;
final String city;
final String state;
final String postalCode;
final double salesTax;
final double yearToDateBalance;
final double latitude;
final double longitude;
final List<String>? shippingTo;
final String documentType = "warehouse";
const Warehouse(
this.warehouseId,
this.name,
this.address1,
this.address2,
this.city,
this.state,
this.postalCode,
this.salesTax,
this.yearToDateBalance,
this.latitude,
this.longitude,
this.shippingTo);
@override
String toString(){
return name;
}
factory Warehouse.fromJson(Map<String, dynamic> json) =>
_$WarehouseFromJson(json);
Map<String, dynamic> toJson() => _$WarehouseToJson(this);
}
StockItem データクラス
もしある人が “「アイテム」” それはそのデータベースから取得され、そのデータベース内で Data Class の型として保存されます。 StockItem.
@JsonSerializable(explicitToJson: true)
class StockItem {
String itemId;
String name;
double price;
String description;
String style;
String documentType = "item";
StockItem(this.itemId, this.name, this.price, this.description, this.style);
factory StockItem.fromJson(Map<String, dynamic> json) =>
_$StockItemFromJson(json);
Map<String, dynamic> toJson() => _$StockItemToJson(this);
}
バッチ操作
一度に複数のデータベースに変更を加える場合は、それらをまとめて行う方が速くなります。バッチ操作は依然としてトランザクション処理です。レプリカライザーによって管理されているものを含め、他のデータベースインスタンスはバッチ操作を実行するコードの実行中に変更を行うことはできません。また、他のインスタンスは部分的な変更は確認できません。バッチ操作はデータを迅速にロードするのに非常に便利です。ここでは、データベースにランダムなサンプルデータをロードするためにそれらを使用します。.
サンプルデータの読み込みをトリガーする
ユーザーがサンプルデータを読み込むには、
- 任意のメールアドレスとパスワードでアプリにログインしてください。.
- 画面左上の「ドロワー」メニューアイコンをタップしてください。
- [開発者]メニュー項目をタップする
- [サンプルデータの読み込み]ボタンをタップします
Loading the Sample Data – Widget and Bloc
全体のプロセスを確認するため、まず開きます。 developer_menu_widget.dart ファイルを選択して、 build function. This function defines the button and calls context.read<DevDataLoadBloc>.add(DevDataLoadStartEvent()) when the *onPressed イベントが呼び出されます。.
Padding(
padding: const EdgeInsets.all(16.0),
child: OutlinedButton(
key: const Key('menu_sample_data'),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.only(
top: 20, bottom: 20, left: 60, right: 60),
backgroundColor: Theme.of(context).backgroundColor,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
),
onPressed: () => {
context
.read<DevDataLoadBloc>()
.add(DevDataLoadStartEvent())
},
child: const Text("Load Sample Data"),
),
),
- 次に、開きます dev_data_load_bloc.dart ファイルを選択して、
_initialize()メソッド。.
Future<void> _initialize(
DevDataLoadEvent event, Emitter<DevDataLoadState> emit) async {
try {
//start loading data into collection
emit(const DevDataLoadState(status: DevDataLoadStatus.loading));
//call the data loader
await _projectRepository.loadSampleData();
//validate that we added some projects
var projectCount = await _projectRepository.count();
if (projectCount > 0) {
emit(const DevDataLoadState(
status: DevDataLoadStatus.success, error: ''));
} else {
emit(const DevDataLoadState(
status: DevDataLoadStatus.failed,
error: 'Project Count is still zero so no projects were added. Please check logs for more information on what failed.'));
}
} catch (e) {
var error = state.copyWith(DevDataLoadStatus.failed, e.toString());
emit(error);
debugPrint(e.toString());
}
}
- This method is defined as Future
with the async keyword in order to run asynchronously. This is important because we will be making calls to the database and we don’t want to block the UI thread. - これにより、project repositories loadSampleData 関数が呼び出されます。
Loading the Sample Data – ProjectRepository
Now that it’s clear how the UI and Bloc interact with the repository, open the project_repository.dart ファイルを選択して、 loadSampleData function. You can see by the method signature that it’s using Future そして async. By using the asynchronous calls and the Database.openAsync function, we keep database operations from blocking the main UI thread.
Future<void> loadSampleData() async {
- 次に、必要なランダムなデータを生成するために使用するサービスとデータを定義する必要があります。.
var currentUser = await _authenticationService.getCurrentUser();
var warehouses = await _warehouseRepository.get();
var stockItems = await _stockItemRepository.get();
- 作成者と変更者フィールドに設定される現在のログインユーザーを取得し、そのプロジェクトがどのチームに割り当てられているかを確認します。.
- 倉庫リポジトリを使用して倉庫のコレクションを取得します。これは、この学習パスの前回のパートで説明した構築済みのデータベースを使用します。.
- 在庫アイテムのリポジトリを使用して、在庫アイテムのコレクションを取得します。これは、この学習パスの前回のパートで説明した、事前に構築されたデータベースを使用しています。.
- Next we get a reference to the inventoryDatabase from the DatabaseProvider. Since the database could be null, we use an if statement to check if it’s null or not.
final db = _databaseProvider.inventoryDatabase;
if (db != null) {
- Finally, we use the database.inBatch function to define a unit of work to add in our random projects to the database using a JSON formatted string by encoding our Project object using the standard Dart JSON encoding library.
/* batch operations for saving multiple documents is a faster way to process
groups of documents at once */
db.inBatch(() async {
// <1>
//create 12 new projects with random data
var uuid = const Uuid();
final random = Random();
const minYear = 2022;
const maxYear = 2025;
const minMonth = 1;
const maxMonth = 12;
const minDay = 1;
const maxDay = 28;
var date = DateTime.now();
//create 12 new projects with random data
// <2>
for (var projectIndex = 0; projectIndex <= 11; projectIndex++) {
//get data items to create project
String projectId = uuid.v4();
var warehouse = warehouses[projectIndex]; // <3>
var yearRandom = minYear + random.nextInt(maxYear - minYear);
var monthRandom = minMonth + random.nextInt(maxMonth - minMonth);
var dayRandom = minDay + random.nextInt(maxDay - minDay);
var dueDate = DateTime.utc(yearRandom, monthRandom, dayRandom);
//create project
var projectDocument = Project(
//<4>
projectId: projectId,
name: '${warehouse.name} Audit',
description:
'Audit of warehouse stock located in ${warehouse.city}, ${warehouse.state}.',
isComplete: false,
dueDate: dueDate,
warehouse: warehouse,
team: currentUser!.team,
createdBy: currentUser.username,
createdOn: date,
modifiedBy: currentUser.username,
modifiedOn: date);
var didSave = await save(projectDocument); // <5>
if (didSave) {
// <6>
//create random audit counts per project // <7>
for (var auditIndex = 0; auditIndex <= 49; auditIndex++) {
var auditId = uuid.v4();
var stockCount = 1 + random.nextInt(10000 - 1);
var stockItemIndex = random.nextInt(stockItems.length);
var stockItem = stockItems[stockItemIndex];
var auditDocument = Audit(
auditId: auditId,
projectId: projectId,
stockItem: stockItem,
auditCount: stockCount,
notes:
'Found item ${stockItem.name} - ${stockItem.description} in warehouse',
team: currentUser.team,
createdBy: currentUser.username,
modifiedBy: currentUser.username,
createdOn: date,
modifiedOn: date);
await _auditRepository.save(auditDocument);
}
}
}
});
- Call the database inBatch function a definition of processing multiple documents to be added to the database.
- Define a loop to add in 12 new project documents to the database
- 倉庫のコレクションからプロジェクトドキュメントに組み込む倉庫を取得する
- ステップ3の倉庫データとランダムなデータで新しいProjectオブジェクトを作成する
- ドキュメントをデータベースに保存する
- 各プロジェクトのランダムな監査項目を作成するために、同じような手順を繰り返します。
ご注意ください: In this example we are using objects and JSON serialization to save it to the database. This is an alternative API to using a
Map<String, Object?>as we did in the key value part of our learning path. Developers that are used to working with JSON encoding and decoding might find this pattern more comfortable to save data to the database.
試してみてください
- このアプリはエミュレータで実行されている必要があります。.
- 任意のメールアドレスとパスワードでアプリにログインしてください。以下の値を利用しましょう。 “demo@example.com“ そして “「P@ssw0rd12」” それぞれユーザー ID フィールドとパスワード フィールドです。これが初めてこの設定を行う場合、 何でも ユーザーがアプリにログインすると、プリビルドされたデータベースがアプリバンドルから読み込まれます。さらに、チーム固有の新しいデータベースが作成/開かれます。.
- 画面左上の「ドロワー」メニューアイコンをタップしてください。
- [開発者]メニュー項目をタップする
- [サンプルデータの読み込み]ボタンをタップします
- 画面左上の「ドロワー」メニューアイコンをタップしてください。
- ホームメニュー項目をタップする

現在、スクロールできる12のサンプルプロジェクトが表示されます。.
Visual Studio Code プラグインを使用したデータレビュー
Visual Studio Code には Couchbase Lite 用のプラグインがあり、データベース内のドキュメントを開いて確認できます。これはアプリのデバッグやテストに役立ちます。Visual Studio Code をダウンロードするには、リンクに従ってください。 これ.
エミュレータからコンピューター上のフォルダにファイルを保存する
ご注意ください: The previous tutorial in this learning path on pre-built databases showed you how to locate the database files on an Android Emulator or iOS Simulator. Please refer to that tutorial for instructions on how to find the path.
For Android: To open the database, you must first copy it from the Emulator to our local computer. To this open Device File Explorer in Android and browse to the local of our applications files folder as shown above. Once in the directory, locate the directory team1_inventory.cblite2 ディレクトリを開いて、その中のすべてのファイルを表示します。すべてのファイルを選択し、ポップアップメニューから右クリックして「名前を付けて保存」を選択して、アクセスできる場所にファイルを保存します。この手順は次のステップで利用します。.

For iOS: To open the database, you must first copy the team1_inventory.cblite2 directory from the simulator folder to a seperate location so we don’t break the database. It’s recommended to copy the database file from the simulators folder to a folder in your users home directory that you can access with Visual Studio Code.
Visual Studio CodeにCoucbase Liteプラグインをインストールする
Visual Studio Code を開き、メニューから「拡張機能」アイコンを選択します。検索ボックスに「 “「Couchbase Lite」” そして「Enter」キーを押します。Couchbase Liteのリストを選択し、「インストール」ボタンをクリックします。.

Visual Studio Codeでデータベースを開く
Visual Studio Code を開いて、「ファイル」をクリックし、「フォルダを開く」を選択します。データベースファイルを保存したフォルダに移動し、[開く]をクリックします。次に、team1_inventory.cblite2フォルダを選択し、右クリックして[データベースを開く]を選択します。Visual Studio Code のファイルブラウザーにCBLITE EXPLORERという新しいオプションが表示されるはずです。このセクションを開くと、データベースが表示され、ファイルの一覧が表示されます。各ファイルのリストにある四角いアイコンをクリックすると、ドキュメント内のフィールドの一覧が表示されます。ドキュメントを開くには、ドキュメント名をクリックして[開く]を選択します。 “「ドキュメントを取得」”.

文書はテキストエディタで開きます。文書のフォーマットを行うには、「表示」を選択し、「コマンドペイン」を選択します。開いたボックスに「 “「フォーマットドキュメント」”. 表示された「ドキュメントのフォーマット」オプションを選択します。.

これにより文書の読みやすさが向上します。これで文書をスクロールしてデータを確認することができます。.
さらに詳しく
私たちの学習のこのステップを完了してくれてありがとう!
この学習パスのステップでは、バッチ操作を使用してCouchbase Liteデータベースに10のサンプルプロジェクトを追加する方法の例を説明しました。詳しいドキュメントについては以下のリンクを参照してください。また、Query Builderを使用してプロジェクト一覧画面をレンダリングする方法についても、次のステップに進んで学習してください。.