Khóa học miễn phí IndexedDB – Object Stores nhận dự án làm có lương

IndexedDB – Object Stores



Object stores are the data storage of IndexedDB. It is where data is stored. A database may have multiple object stores. Think of them as tables in RDBMS where we store data based on the type of data we want to store.

To ensure database integrity, object stores can only be created and removed using the callback function idb.open(). It contains a method named createObjectStore() which is used to create an object-store.

Creating object Stores

You can create an object store using the createObjectStore() method. Following is the syntax of this method −

IDBDatabase.createObjectStore(name);
Or,
IDBDatabase.createObjectStore(name, options);

Where,

  • The name is the name of the object store.
  • The options object can let us define various configuration properties.

Example

Following example creates a new database and creates a object store in it −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Creating Object Store</title>
</head>
<body>
   <script>
      var request = indexedDB.open("myDatabase", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("customers");
         document.write("Object store Created Successfully...");
      };
   </script>
</body>
</html>

Output

On executing, the above program displays the following message on the browser.

Object store Created Successfully...

Verification

If the above program is executed successfully if you expand “myDatabase” you can see the newly created object-store.

Customers File

Defining primary keys

Similar to RDBMS we need primary keys to uniquely define some data in an object store. It can be done in 2 ways using a key path or a key generator.

Keypath and Key generator

A key path is a property that always exists and contains a unique value. We can choose a unique value such as an email address for example.

A key generator creates a unique value for every object added to the object store. By default, if we don”t mention a key generator comes into the picture. Ex, auto-increment.

Syntax

Following is the syntax ro create a keypath on an object store.

var objectStore = db.createObjectStore("ObjectStoreName", { keyPath: "primary key, autoincrement/autoDecrement : true" });

Example

In the example given below, we are creating a keypath to an object store using JavaScript −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>keypath</title>
</head>
<body>
   <script>
      var request = indexedDB.open("myDtabase", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("customers",{keyPath:"id", autoIncrement:true});
         document.write("Object store Created Successfully...");
      };
   </script>
</body>
</html>

Output

On executing the above example, it will display the following text on the browser −

Object store Created Successfully...

Verification

If the above program is executed successfully if you expand “myDatabase” you can see the newly created object store, if you click on it you can observe that the keypath is created for “id”.

Key Path

When new object stores are created they are mentioned in the IndexedDB folders like above.

You can use both a keypath and a key generator. If the data is always unique we can use a keypath else if the value changes you can use a key generator, if you want to change the values for every value but want to give a value that uniquely represents the store we can use both.

Defining Indexes

Indexes are a kind of object-store. They are used to retrieve data from the reference object, stored by a specified property. An index uses the specified property as its key path instead of the reference store”s primary key.

To create an index, you need to call the createIndex() method on an object store instance.

Syntax

Following is the syntax of the createIndex() method −

var myIDBIndex = objectStore.createIndex(indexName, keyPath);
var myIDBIndex = objectStore.createIndex(indexName, keyPath, Parameters);

Where,

  • An indexName is the name of the index created.

  • Keypath is the primary definition while creating an object store

  • The value of the last parameter can be unique or multi-entry

    • In case you “pass unique: true”. The index will not allow duplicate values for a single key.

    • If you pass “multi-entry: true”. The index will add an entry for each array element when the keyPath resolves to an Array. If false, it will add one single entry containing the Array.

Example

The following JavaScript example demonstrates how to create indexes.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>OPENING A DATABASE</title>
</head>
<body>
   <script>
      const dbName = "myDB";
      const studentdata = [
         {name : "jason" , rollno: "160218737028" , branch : "IT"},
         {name : "lokesh" , rollno: "160218735020" , branch : "CSE"},
         {name : "tarun" , rollno: "160218733057" , branch : "EEE"},
         {name : "pranith" , rollno: "160218737029" , branch : "IT"}
      ];
      var request = indexedDB.open("myDB", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("student",{ keyPath :"rollno" });
         objectStore.createIndex("name", "name", { unique: false });
         objectStore.createIndex("branch", "branch", { unique: false });
         objectStore.transaction.oncomplete = event => {
            var objectStore = db.transaction("student", "readwrite").objectStore("student");
            studentdata.forEach(function(student) {
               objectStore.add(student);
            });
         };
      };
   </script>
</body>
</html>

Output

If you go and verify the contents of the IndexedDB database myDB and expand it youj can observe the created table as −

Key Values

If you click on the name and student values you can observe the index values as −

Name index

# Key(Key path:”name”) Primary key (Key path:”rollno”) Value
0 “jason” “160218737028”

{name: ”jason”, rollno: ”160218737028”, branch:

1. branch: “IT”

2. name: “jason”

3. rollno: “160218737028”

1 “lokesh” “160218735020”

{name: ”lokesh”, rollno: ”160218735020”, branch: ”CSE”}

1. branch: “CSE”

2. name: “lokesh”

3. rollno: “160218735020”

2 “pranith” “160218737029”

{name: ”pranith”, rollno: ”160218737029”, branch: ”IT”}

1. branch: “IT”

2. name: “pranith”

3. rollno: “160218737029”

3 “tarun” “160218733057”

{name: ”tarun”, rollno: ”160218733057”, branch: ”EEE”}

1. branch: “EEE”

2. name: “tarun”

3. rollno: “160218733057”

Branch Index

# Key(Key path:”branch”) Primary key (Key path:”rollno”) Value
0 “CSE” “160218735020”

{name:”lokesh”, rollno:”160218735020”, branch: ”CSE”}

1. branch: “CSE”

2. name: “lokesh”

3. rollno: “160218735020”

1 “EEE” “160218733057”

{name:”tarun”, rollno: ”160218733057”, branch: ”EEE”}

1. branch: “EEE”

2. name: “tarun”

3. rollno: “160218733057”

2 “IT” “160218737028”

{name:”jason”, rollno: ”160218737028”, branch: ”IT”}

1. branch: “IT”

2. name: “jason”

3. rollno: “160218737028”

3 “IT” “160218737029”

{name:”pranith”, rollno: ”160218737029”, branch: ”IT”}

1. branch: “IT”

2. name: “pranith”

3. rollno: “160218737029”

Deleting Object Store

Object stores are similar to tables in a database and when a table is not needed we delete it. Similarly, you can delete an object store if it is no longer in use. To delete the object store you need to invoke the deleteObjectStore() function.

Syntax

Following is the syntax of the deleteObjectStore() function −

db.deleteObjectStore("store_name");

Where, store_name is the name of the object store you need to delete.

Example

Let us look at a JavaScript example that deletes an object store which is no longer necessary −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>OPENING A DATABASE</title>
</head>
<body>
   <script>
      const dbName = "Database";
      var request = indexedDB.open("Database", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("student",{ keyPath :"rollno" } );
         var objstore = db.createObjectStore("college",{autoIncrement : true});
         db.deleteObjectStore("college");
      };
   </script>
</body>
</html>

Output

Before and After deleting the object store in the IndexedDB folder in the browser.

Database
   College − object store
   Student − object store
      Name − index
      Branch − index

Database
   Student − object store
      Name − index
      Branch − index

Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc