Skip to content

使用 getAll() 函数

虽然你可以使用 get() 方法逐个检索对象,或者使用游标进行迭代,但一个非常常见的需求是同时获取多条记录。getAll() 方法是从存储或索引中检索所有匹配特定查询的对象的现代、高效方法。

const results = await objectStore.getAll([query], [count]);
const indexResults = await index.getAll([query], [count]);

objectStore 和 index 对象都支持 getAll()。参数是可选的:

  • query:一个键或 IDBKeyRange,用于过滤结果。如果省略,将返回存储/索引中的所有对象。
  • count:一个整数,指定要检索的最大对象数量。

getAll() 方法很方便,但要留意其内存使用情况。它会将所有匹配的对象加载到内存中的一个数组里。对于极其庞大的数据集(例如,数十万条记录),这可能会给浏览器带来压力。在这种情况下,使用游标逐条处理记录是一种更节省内存的方法。

示例:检索所有数据和数据子集

Section titled “示例:检索所有数据和数据子集”

在以下示例中,我们创建一个 ‘tasks’ 数据库。我们首先使用 getAll() 检索所有任务,然后再次使用查询,只检索特定项目中的任务。

<!DOCTYPE html>
<html lang="en">
<head>
<title>IndexedDB getAll() 示例</title>
</head>
<body>
<h1>检查控制台输出</h1>
<script type="module">
import { openDB } from 'https://cdn.jsdelivr.net/npm/idb@7/build/index.js';
async function runDemo() {
const db = await openDB('taskManagerDB', 1, {
upgrade(db) {
const store = db.createObjectStore('tasks', { keyPath: 'id', autoIncrement: true });
store.createIndex('projectIdx', 'project');
},
});
const tx = db.transaction('tasks', 'readwrite');
await Promise.all([
tx.store.add({ text: 'Design UI mockups', project: 'Website' }),
tx.store.add({ text: 'Develop API endpoints', project: 'Backend' }),
tx.store.add({ text: 'Implement frontend logic', project: 'Website' }),
tx.store.add({ text: 'Write documentation', project: 'Backend' }),
]);
await tx.done;
// 1. 从对象存储中获取所有任务
const allTasks = await db.getAll('tasks');
console.log('--- All Tasks ---');
console.table(allTasks);
// 2. 使用索引获取 'Website' 项目的所有任务
const websiteTasks = await db.getAllFromIndex('tasks', 'projectIdx', 'Website');
console.log("--- 'Website' Project Tasks ---");
console.table(websiteTasks);
}
runDemo().catch(console.error);
</script>
</body>
</html>
--- All Tasks ---
(console.table of 4 tasks)
--- 'Website' Project Tasks ---
(console.table of 2 tasks: 'Design UI mockups' and 'Implement frontend logic')