前回の RxDB は、PouchDB のアダプタが使えますよ、といっていた。
今回はその Pouch DB だ。
PouchDB, the JavaScript Database that Syncs!
https://pouchdb.com/
簡単に使えるならなんでもいいんだけどね。
find() は別になっているのでインストールがいるのだった。
npm i pouchdb pouchdb-find
01: const PouchDB = require('pouchdb');
02: PouchDB.plugin(require('pouchdb-find'));
03:
04: const db = new PouchDB('kittens');
05:
06: const fn = async () => {
07: db.bulkDocs([
08: {
09: name: "yoshida",
10: color: "green",
11: healthpoints: 30,
12: },
13: {
14: name: "yoshio",
15: color: "blown",
16: healthpoints: 33,
17: },
18: {
19: name: "momo",
20: color: "pink",
21: healthpoints: 9,
22: },
23: ]);
24:
25: await db.createIndex({
26: index: {fields: ['healthpoints']}
27: });
28: const resHealth = await db.find({
29: selector: {healthpoints: {$exists: true}},
30: sort: ['healthpoints'],
31: });
32: for (let lp = 0; lp < resHealth.docs.length; lp++) {
33: console.log(resHealth.docs[lp].name);
34: }
35: console.log();
36:
37: await db.createIndex({
38: index: {fields: ['color']}
39: });
40: const resColor = await db.find({
41: selector: {color: {$exists: true}},
42: sort: ['color'],
43: });
44: for (let lp = 0; lp < resColor.docs.length; lp++) {
45: console.log(resColor.docs[lp].name);
46: }
47:
48: await db.destroy();
49: };
50: fn();
createIndex()が、fields を列挙したらその分作られるのかと思ったのだが、それぞれ作ることになるようだ。戻り値で"created" か "exists" が取ってこれるが、存在するなら作らないと書いてあるので、そんなに気にしなくてよいのか。
また、createIndex() した後に put() したら再度 createIndex() がいるのかと思ったが、そうでもないようだ。今のコレクションに対してインデックスを作るという意味ではないのか。
TypeScriptの場合はこんな書き方で良いのかな?
find() したドキュメントがうまいことプロパティにアクセスできなかったので as を使ってキャストしてしまった。よいのかどうかわからん。
01: import * as PouchDB from 'pouchdb';
02:
03: PouchDB.plugin(require('pouchdb-find'));
04:
05: const db = new PouchDB.default('kittens');
06:
07: type dbType = {
08: _id: string;
09: _rev: string;
10: name: string;
11: color: string;
12: healthpoints: number;
13: };
14: const fn = async () => {
15: db.bulkDocs([
16: {
17: name: "yoshida",
18: color: "green",
19: healthpoints: 30,
20: },
21: {
22: name: "yoshio",
23: color: "blown",
24: healthpoints: 33,
25: },
26: {
27: name: "momo",
28: color: "pink",
29: healthpoints: 9,
30: },
31: ]);
32:
33: let idxRes = await db.createIndex({
34: index: { fields: ['healthpoints'] }
35: });
36: const resHealth = await db.find({
37: selector: { healthpoints: { $exists: true } },
38: sort: ['healthpoints'],
39: });
40: for (let lp = 0; lp < resHealth.docs.length; lp++) {
41: const r = resHealth.docs[lp] as dbType;
42: console.log(r.name);
43: }
44: console.log();
45:
46: idxRes = await db.createIndex({
47: index: { fields: ['color'] }
48: });
49: const resColor = await db.find({
50: selector: { color: { $exists: true } },
51: sort: ['color'],
52: });
53: for (let lp = 0; lp < resColor.docs.length; lp++) {
54: const r = resColor.docs[lp] as dbType;
55: console.log(r.name);
56: }
57:
58: await db.destroy();
59: };
60: fn();