Opening a database
Learn to open a database with indexedDB.open and handle version changes.
Opening a database
You open an IndexedDB database with indexedDB.open(name, version). name is the database name and version is an integer. If the database does not exist, it is created; otherwise it is opened at the given version.
const request = indexedDB.open('NotesDB', 1);The call returns an IDBOpenDBRequest. When the operation finishes, onsuccess fires; on failure, onerror; when the structure changes, onupgradeneeded.
Request events
You catch the outcome of the open request through event listeners. request.onsuccess runs when the database opens, request.onerror runs on failure, and request.onupgradeneeded runs when the structure changes.
request.onsuccess = function(event) {
const db = event.target.result;
};The event's target.result property is the open IDBDatabase instance you use for the next steps.
Exercise Open NotesDB and attach listeners
Open the 'NotesDB' database at version 1 with indexedDB.open and assign it to a request variable. Assign a function to request.onsuccess, request.onerror and request.onupgradeneeded. Inside onerror, log 'error' with console.log.
Show example solution
const request = indexedDB.open('NotesDB', 1);
request.onsuccess = function(event) {};
request.onerror = function(event) {
console.log('error');
};
request.onupgradeneeded = function(event) {};
Test yourself
-
When does the onupgradeneeded event fire?
- Only the first time the database opens
- When the database version changes or it is first created
- After every add operation
- When the browser closes
Show answer
When the database version changes or it is first created — Correct! onupgradeneeded is the only safe place to change the structure.
-
Open the database at version 2
const request = indexedDB.____('NotesDB', 2);Show answer
const request = indexedDB.open('NotesDB', 2); -
Match events to their meaning
- onsuccess
- operation succeeded
- onerror
- an error occurred
- onupgradeneeded
- version changed
- target.result
- database instance