戻る

exists(getKey)
indexedDB

getKey
インデックスに対して最初に一致した1件だけを返します。

[サンプル]
copy
async function testExistsTest1(dbName, storeName, f1Value, f2Value)
{
	const db = await databaseOpen(dbName);
	const result = await runTx(db, storeName, "readonly", (store) => 
	{
		return new Promise((resolve, reject) => 
		{
			const index = store.index("f1_f2");
			//search f1 and f2 compound index
			const request = index.getKey([f1Value, f2Value]);
			request.onsuccess = () => 
			{
				//if exists record, return key is true.
				resolve(request.result !== undefined);
			};
			request.onerror = () => reject(request.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;
}
testExistsTest1("aaa", "t2", 1, 2)
.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" });
});
*/

インデックスに対してget()もしくはgetKey()を実行すると最初に一致した1件だけを返します。
これを利用した存在チェックをexistsの代用できます。
const request = index.getKey([f1Value, f2Value]);
複合インデックスで検索しています。
request.onsuccess = () =>
{
resolve(request.result !== undefined);
};
結果を返します。
存在しているとtrue以外はfalseを返します。

request.result !== undefined
一致するレコードがない場合はundefinedになります。
IndexedDB API の仕様で「見つからなかった場合は undefined を返す」と定義されています。



戻る


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