Indexeddb 简明教程

IndexedDB - Using getAll() Function

在前几部分中,我们一次只从存储中检索对象。现在,我们可以检索所有数据或对象存储的子集。获取 all 方法使用 getAll() 函数返回对象存储中的所有对象

In the previous sections, we only retrieved objects from the store one at a time. Now we can retrieve all the data or subsets of the object stores. The get all method returns all the objects in the object store using the getAll() function

Syntax

ObjectStore.getAll(optionalConstraint);

我们可以直接调用 getAll() 以返回存储在对象库中的所有对象,或者我们可以指定一个可选约束,例如从汽车数据库中获得红色轿车

We can directly call getAll() to return all the objects stored in the object store or else we can specify an optional constraint for example red colored cars from a car database

Example

在以下示例脚本中,我们正在调用 getAll() 方法以一次性返回存储在对象库中的所有对象

In the following example script, we are calling the getAll() method to return all the objects stored in the object store at once −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
</head>
<body>
   <script>
      const request = indexedDB.open("botdatabase",1);
      request.onupgradeneeded = function(){
         const db = request.result;
         const store = db.createObjectStore("bots",{ keyPath: "id"});
         store.createIndex("branch_db",["branch"],{unique: false});
      }
      request.onsuccess = function(){
         document.write("database opened successfully");
         const db = request.result;
         const transaction=db.transaction("bots","readwrite");
         const store = transaction.objectStore("bots");
         const branchIndex = store.index("branch_db");
         store.add({id: 1, name: "jason",branch: "IT"});
         store.add({id: 2, name: "praneeth",branch: "CSE"});
         store.add({id: 3, name: "palli",branch: "EEE"});
         store.add({id: 4, name: "abdul",branch: "IT"});
         store.put({id: 4, name: "deevana",branch: "CSE"});
         const query = branchIndex.getAll(["IT"]);
         query.onsuccess = function(){
            document.write("query",query.result);
         }
         transaction.oncomplete = function(){
            db.close;
         }
      }
   </script>
</body>
</html>

Output

database opened successfully
query (1) [{...}]
arg1:(1) [{...}]
0:{id: 1, name: 'jason', branch: 'IT'}
length:1
[[Prototype]]:Array(0)
[[Prototype]]:Object