戻る

exists(openCursor)
indexedDB

カーソル
レコードオブジェクトの条件と一致するか判定した結果を返します。

[サンプル]
copy
async function testExistsTest2(dbName, storeName, fn)
{
//console.log("dbName:"+dbName+" storeName:"+storeName+" fn:"+fn);
	const db = await databaseOpen(dbName);
	const result = await runTx(db, storeName, "readonly", (store) => 
	{
		return new Promise((resolve, reject) => 
		{
			const req = store.openCursor();
			req.onsuccess = (event) => 
			{
				const cursor = event.target.result;
				if (cursor) 
				{
					if (fn(cursor.value)) 
					{
						resolve(true); // if it is found, it ends immediately.
						return;
					}
					cursor.continue();
				} 
				else 
				{
					resolve(false);//cases where it was not found until the end.
				}
			};
			req.onerror = () => reject(req.error);
		});
	});
	
	db.close();

	return result;
}
function databaseOpen(dbName) 
{
	return new Promise((resolve, reject) => 
	{
		const req = indexedDB.open(dbName);
		req.onsuccess = (event) => 
		{
			resolve(event.target.result);
		};
		req.onerror = () => reject(req.error);
	});
}
function waitForTx(tx) 
{
	return new Promise((resolve, reject) => 
	{
		tx.oncomplete = () => resolve();
		tx.onabort = () => reject(tx.error ?? new Error("Transaction aborted"));
		tx.onerror = () => reject(tx.error);
	});
}

async function runTx(db, storeName, mode, work) 
{
	const tx = db.transaction([storeName], mode);
	const store = tx.objectStore(storeName);
	const result = await work(store);
	await waitForTx(tx);
	return result;
}
testExistsTest2("aaa", "t2", rec => rec.f1 == 1 && rec.f2 >= 1)
.then(result => 
{
	console.log(result);
})
.catch(error => {
	console.error("group by error:", error);
});
//[sample data]
/*
await runTx("aaa", "t2", "readwrite", (store) => 
{
	store.add({ f0: 0, f1: 1, f2: 2, f3: 1, f4: "1,2,1" });
	store.add({ f0: 1, f1: 1, f2: 1, f3: 1, f4: "1,1,1" });
	store.add({ f0: 2, f1: 1, f2: 3, f3: 1, f4: "1,3,1" });
	store.add({ f0: 3, f1: 3, f2: 1, f3: 1, f4: "3,1,1" });
	store.add({ f0: 4, f1: 3, f2: 4, f3: 1, f4: "4,4,1" });
	store.add({ f0: 5, f1: 2, f2: 1, f3: 3, f4: "2,1,3" });
	store.add({ f0: 6, f1: 2, f2: 1, f3: 2, f4: "2,1,2" });
	store.add({ f0: 7, f1: 2, f2: 1, f3: 1, f4: "2,1,1" });
});
*/

条件が複雑でインデックスのみでは対応できない場合はカーソルを使う方法です。
if (fn(cursor.value))
カーソルに条件が一致する場合はtrueを返します。
resolve(false);
カーソルが終了して、最後まで見つからない場合はfalseを返します。
request.result !== undefined
一致するレコードがない場合はundefinedになります。
IndexedDB API の仕様で「見つからなかった場合は undefined を返す」と定義されています。



戻る


著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。