Indexeddb 添加新值而不是更新现有值

2024-04-29

当尝试更新其中的记录时索引数据库使用put方法,看起来是创造了新的价值而不是改变。根据MDN https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore.put这是更新记录的方法,但我没有得到预期的结果。有任何想法吗?这是我的代码示例。

/*
    @keys initalisation
*/
extension.onupgradeneeded = function (event) {
    database = event.target.result;

    if (!database.objectStoreNames.contains('profile')) {

        var _profile = database.createObjectStore('profile', { autoIncrement: true });

        _profile.createIndex('default', 'default', { unique: true });
        _profile.createIndex('username', 'username', { unique: true });

        _profile.transaction.oncomplete = function (_oncompleteEvent) {

             app.database.store(database, 'profile', {
                default: true,
                username: 'my name', 
                image: 'images/svg/menu.svg' 
             });
        };
}

var app = {
    database: {
        update: function (_database, _datakeys, _key, _value, _function) {
            /*
                @pass database object, array / string, string, object, callback
            */
            var _updateRequest = _database.transaction(_datakeys, "readwrite").objectStore(_key).put(_value);

            _updateRequest.onerror = function (event) {
                try {
                    _function.error(event);
                } catch(err) {
                    console.log('An error was encountered', event.target.error.name);
                }
            };

            _updateRequest.onsuccess = function (event) {
                try {
                    _function.success(event);
                } catch (error) {
                    _function(event);
                }
            };
        }
    }
};

/*
    @how I call the function
*/

app.database.update(database, 'profile', 'profile', {default: false, username: 'hello world', image: 'http://imagepath.com' }, {
    error: function () {
        alert('failed');
    },
    success: function (returnedData) {
        console.log(returnedData);
    }
);

您使用的是内嵌键还是外嵌键?

  • 如果是内联,则需要设置id(无论你命名它)使用之前对象中的属性store.put.
  • 如果超出范围,则需要通过id属性值作为第二个参数store.put.

编辑:如果您不知道按键是内联还是外联,请查看下列的 https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB:

每个对象存储都必须有一个在其数据库中唯一的名称。对象存储可以选择具有密钥生成器和密钥路径。如果对象存储有键路径,则它使用内联键;否则,它正在使用外线键。

如果您使用内联,并且正在设置属性,并且它仍在执行插入而不是更新,请尝试console.log('The object passed to put is %o', objToPut);打电话之前store.put,并验证是否id属性(或者您命名为商店主键的任何内容)已定义并具有预期值(其 id)。

如果您没有使用存储键,那么所有放入都将是插入,因为indexedDB无法知道要更新哪个对象。如果您无论如何都想这样做,也许您可​​以在要更改的对象上使用 openCursor ,然后使用cursor.update 来替换该对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Indexeddb 添加新值而不是更新现有值 的相关文章

随机推荐