如何使用自动增量键更新 IndexedDB 项目?

How to update an IndexedDB item with autoincrement key?

我使用自动增量创建了一个对象存储:db.createObjectStore("items", {autoIncrement:true});

现在我希望能够在给定键和新值的情况下更新项目,所以我编写了这个函数:

let updateItem = (key, newData) => {
    let objectStore = db.transaction(["items"], "readwrite").objectStore("items");
    let request = objectStore.get(key);
    request.onsuccess = (e) => {
        let data = e.target.result;
        Object.assign(data, newData);
        let requestUpdate = objectStore.put(data);      
    };
}

但是,它没有更新值,而是使用新数据创建了一个新项目。我认为这是有道理的,因为 e.target.result 不包含有关其密钥的任何信息。那么如何更新此类对象存储中的元素?

您需要添加一个键作为第二个参数,例如objectStore.put(data, key)

key

The primary key of the record you want to update (e.g. from IDBCursor.primaryKey). This is only needed for object stores that have an autoIncrement primary key, therefore the key is not in a field on the record object. In such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify.

-- IDBObjectStore.put() - Web APIs | MDN

我使用 cursor.update() 找到了另一个解决方案:

let updateItem = (key, newData) => {
    let objectStore = db.transaction("items","readwrite").objectStore("items");
    objectStore.openCursor().onsuccess = (e) => {
        let cursor = e.target.result;
        if (cursor && cursor.key == key) {
            cursor.update(Object.assign(cursor.value, newData));
            cursor.continue();
        }
    };
}