IndexedDB 的 get() 返回 undefined,怎么判断记录是否存在?

作者:像素猫

时间:2026-12-01

浏览:560

用同一个 IndexedDB 对象仓库对照 get()、getKey() 和 openCursor(),区分主键缺失与已存值为 undefined。

文章目录

从 IndexedDB 读草稿时,看到 undefined,你可能会直接打开一份空白草稿。但原来的记录也许还在,只是存进去的值刚好是 undefined。如果页面只想决定该恢复还是新建,可以直接查主键。

让两个主键读出同一个值

找一个可以使用 IndexedDB 的 HTTPS 页面,在控制台粘贴下面的代码。它会新建临时数据库,对象仓库 drafts 没有指定 keyPath,所以 put(undefined, 0) 能把 0 当作独立的主键,把 undefined 存进去。主键 1 则留空。

(() => {
  const name = `idb-get-demo-${crypto.randomUUID()}`;
  const open = indexedDB.open(name, 1);

  open.onupgradeneeded = () => {
    const store = open.result.createObjectStore('drafts');
    store.put(undefined, 0);
  };

  open.onerror = () => console.error(open.error);
  open.onsuccess = () => {
    const db = open.result;
    const tx = db.transaction('drafts', 'readonly');
    const store = tx.objectStore('drafts');
    const keys = [0, 1];

    for (const key of keys) {
      const request = store.get(key);
      request.onsuccess = () => {
        console.log(`get(${key}) -> ${request.result}`);
      };
    }

    for (const key of keys) {
      const request = store.getKey(key);
      request.onsuccess = () => {
        const found = request.result;
        console.log(`getKey(${key}) -> ${found}, exists: ${found !== undefined}`);
      };
    }

    tx.oncomplete = () => {
      db.close();
      indexedDB.deleteDatabase(name);
    };
    tx.onabort = () => {
      db.close();
      console.error(tx.error);
    };
  };
})();
主键 0 和 1 的 get 查询都返回 undefined
按代码绘制的前两行预期控制台输出。

前两行都输出 undefined。这是 get() 发出的请求成功后读到的 request.result,从这一项看不出主键有没有命中。

用 getKey() 判断记录是否存在

把同一个主键传给 getKey()。有记录时,request.result 是查到的主键。没有记录时,成功回调里读到的才是 undefined。这里用 found !== undefined 判断。写成 Boolean(found) 会把合法的主键 0 当成没找到。

getKey 查询命中主键 0,主键 1 未命中
按代码绘制的后两行预期控制台输出。

用 openCursor() 同时取值和存在状态

需要同时拿到值和存在状态时,可以在活动事务里传入具体主键,打开一个游标。成功回调里的 request.result 为 null 时,说明没找到记录。有游标时就能直接取 cursor.value。

function readEntry(store, key, onEntry) {
  const request = store.openCursor(key);
  request.onsuccess = () => {
    const cursor = request.result;
    if (cursor === null) {
      onEntry({ exists: false });
      return;
    }

    onEntry({ exists: true, value: cursor.value });
  };
  return request;
}
游标未命中时为 null,命中时即使 value 为 undefined 仍返回 exists 为 true
按示例里的两条成功分支绘制。

想把游标也加进前面的演示,可以先定义 readEntry,再在 open.onsuccess 里两个循环结束后调用 readEntry(store, 0, console.log) 和 readEntry(store, 1, console.log)。主键 0 会得到 { exists: true, value: undefined },主键 1 会得到 { exists: false }。页面就可以按 exists 决定是恢复草稿还是进入新建流程。

命中和未命中都在 onsuccess 里处理。调用方可以给返回的请求设置 onerror,也可以用事务的 onerror 统一处理。这样读库失败时,页面能提示用户重试。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章