update a single field in indexeddb

2.7k Views Asked by At

The following working code is used to setup my question:

myRequest = indexedDB.deleteDatabase('myDatabase')
myRequest.onsuccess = function() {
 var myRequest
 
 myRequest = indexedDB.open('myDatabase')
 myRequest.onupgradeneeded = function(response) {
  var myDatabase
   ,myObjectStore
  
  myDatabase = response.target.result
  myObjectStore = myDatabase.createObjectStore('myData',{autoIncrement:true})
 }
 myRequest.onerror = function(response) {
  debugger
 }
 myRequest.onsuccess = function(response) {
  var myTransaction
   ,myObjectStore
   ,myRequest
   ,obj = {}
  window.myDatabase = response.target.result
  myTransaction = myDatabase.transaction(['myData'],'readwrite')
  myObjectStore = myTransaction.objectStore('myData')
  obj.field1 = 'a'
  obj.field2 = 'b'
  myObjectStore.add(obj)
 }
}

Q: How do I say the equivalent of:

update myData set field2='c' where key=1

Do I have to supply both field1 and field2 in a .put statement?

2

There are 2 best solutions below

2
On BEST ANSWER

Yes, you must put the full object, e.g.

myObjectStore.get(1).onsuccess = function(e) {
  var obj = e.target.result;
  obj.field2 = 'c';
  myObjectStore.put(obj, 1);
};
1
On

myRequest = indexedDB.deleteDatabase('myDatabase')
myRequest.onsuccess = function() {
 var myRequest
 
 myRequest = indexedDB.open('myDatabase')
 myRequest.onupgradeneeded = function(response) {
  var myDatabase
   ,myObjectStore
  
  myDatabase = response.target.result
  myObjectStore = myDatabase.createObjectStore('myData',{autoIncrement:true})
 }
 myRequest.onerror = function(response) {
  debugger
 }
 myRequest.onsuccess = function(response) {
  var myTransaction
   ,myObjectStore
   ,myRequest
   ,obj = {}
  window.myDatabase = response.target.result
  myTransaction = myDatabase.transaction(['myData'],'readwrite')
  myObjectStore = myTransaction.objectStore('myData')
  obj.field1 = 'a'
  obj.field2 = 'b'
  myObjectStore.add(obj)
 }
}

myRequest = indexedDB.deleteDatabase('myDatabase')
myRequest.onsuccess = function() {
 var myRequest
 
 myRequest = indexedDB.open('myDatabase')
 myRequest.onupgradeneeded = function(response) {
  var myDatabase
   ,myObjectStore
  
  myDatabase = response.target.result
  myObjectStore = myDatabase.createObjectStore('myData',{autoIncrement:true})
 }
 myRequest.onerror = function(response) {
  debugger
 }
 myRequest.onsuccess = function(response) {
  var myTransaction
   ,myObjectStore
   ,myRequest
   ,obj = {}
  window.myDatabase = response.target.result
  myTransaction = myDatabase.transaction(['myData'],'readwrite')
  myObjectStore = myTransaction.objectStore('myData')
  obj.field1 = 'a'
  obj.field2 = 'b'
  myObjectStore.add(obj)
 }
}