IndexedDB
Query notes through an index
Add a title index in a versioned upgrade and query a bounded subset instead of loading the entire store.
8 minute lesson
Primary keys answer one access pattern. An index supports a different lookup without scanning every record in application code.
Open database version 2 and add a normalized titleKey index. Existing records need a data migration or a fallback path because an index cannot invent missing property values.
export const db = await openDB('field-notes', 2, {
upgrade(db, oldVersion, newVersion, tx) {
if (oldVersion < 1) {
db.createObjectStore('notes', { keyPath: 'id' })
}
if (oldVersion < 2) {
tx.objectStore('notes').createIndex('by-title', 'titleKey')
}
},
})
const matches = await db.getAllFromIndex('notes', 'by-title', 'trail', 20)
Version checks let a user move directly from any older version. Never assume every browser opened the immediately previous release.
Indexes speed a known read and add work to writes. Add one because the interface queries it, not because the property exists.
The fourth argument bounds this exact-key lookup to twenty records. A growing search interface still needs a deliberate cursor or pagination design.
Upgrade to version 2, migrate existing notes with lowercase titleKey values, and query the index. Test both a fresh database and a direct upgrade from version 1.
Lesson completed