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

Indexeddb adds a new value instead of updating an existing value

本文关键字:更新 添加 新值 Indexeddb      更新时间:2023-09-26

当尝试使用put方法更新indexeddb中的记录时,似乎创建了一个新值而不是更改。根据MDN这是更新记录的方法,但我没有得到预期的结果。什么好主意吗?下面是我的代码示例。

/*
    @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);
    }
);

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

  • 如果是内联的,你需要在使用store.put之前在对象中设置id(无论你叫它什么)属性。
  • 如果脱行,则需要将id属性值作为第二个参数传递给store.put

编辑:如果您不知道键是行内的还是行外的,请查看以下内容:

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

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

如果您没有为存储使用键,那么所有的put都将是insert,因为indexedDB无法知道要更新哪个对象。如果你想这样做,也许你可以在你想改变的对象上使用openCursor,然后使用游标。更新以替换该对象