v145 · Web APIs · Upsert Demo
Upsert Demo
Demonstrates IndexedDB's put() in upsert mode — writing a record creates it; writing again updates it — with no pre-read required.
upsert store
IndexedDB—
DB open—
Current record—
Enter a key/value and click Upsert.
code
// Upsert with put() — no pre-read needed
function upsert(db, storeName, record) {
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, 'readwrite');
const req = tx.objectStore(storeName).put(record);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
// First call: creates the record
await upsert(db, 'kv', { id: 'theme', value: 'light' });
// Second call: replaces the record
await upsert(db, 'kv', { id: 'theme', value: 'dark' });
// Result: { id: 'theme', value: 'dark' }
// No read was needed to achieve this — put() is always upsert.