IndexedDB - Using getAll() Function



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);

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

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
Advertisements