To update an existing data in the database, the put(item, key)
method is used. However, if the requested data doesn't exist, this method creates it and inserts it in the Object Store. This method returns the key
of the stored object as a result.
The method used has two parameters, the first is the object to update or insert, and the second parameter is optional and refers to the key
of the object, this last parameter is only necessary when an autoincrement value is used as the key of the stored objects, since if it is not specified a new object will be created with an automatically generated key.
To update, usually the get(key)
method is first used to get the stored object, then the necessary properties are updated, and finally the put(obj)
method is used with the new object.
function updateStudent(key){
const objectStore = db.transaction('students')
.objectStore('students');
const request = objectStore.get(key);
request.onsuccess = ()=> {
const student = request.result;
// Change the name property
student.name = 'Fulanito';
// Create a request to update
const updateRequest = objectStore.update(student);
updateRequest.onsuccess = () => {
console.log(`Estudent updated, email: ${updateRequest.result}`)
}
}
}
updateStudent('andres@andres.com');
Top comments (1)
I'm puzzled. You say
Some comments have been hidden by the post's author - find out more