gpt4 book ai didi

indexeddb - 更新版本时 indexeddb 数据库出现约束错误,仅此而已

转载 作者:行者123 更新时间:2023-12-01 11:42:54 30 4
gpt4 key购买 nike

我在不做任何其他修改的情况下升级版本时遇到此代码问题,我无法理解原因。

function create_registry() {
var version = 1;
var indexeddb_db = "examples"; // database
var indexeddb_table = "examples_table"; // table

// open the database
var indexeddb_request = indexedDB.open( indexeddb_db, version ); // connect + open database
var db = false;

// if error
indexeddb_request.onerror = function ( event ) {
console.log( event.target );
console.trace();
}

// if success
indexeddb_request.onsuccess = function ( event ) {
console.log( event.target );
console.trace();
}

// if onupgradeneeded
indexeddb_request.onupgradeneeded = function( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
var objectStore = db.createObjectStore( indexeddb_table, { keyPath: 'url' } );
}

}

第一次加载页面时,会创建 indexedDB 对象(数据库)并创建其中的表。一切正常。首先执行 onupgradeneeded,然后启动 onsuccess。

如果我重新加载页面而不做任何更改,一切正常,启动 onsuccess。

但是,如果我更改版本号,则会出现下面提到的错误。 W3C spec of the Indexed Database API 中简要描述了这些错误,但到目前为止这对我没有太大帮助。 onupgradeneeded 执行后,onerror 执行,我有一个 AbortError,但这也没有告诉我更多信息。

Chrome 28 "Uncaught Error: ConstraintError: DOM IDBDatabase Exception 0"

Firefox 22 "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one. "

据我所知,问题是我试图用相同的键路径重新创建相同的对象,但新版本不是让脚本重新创建整个对象吗?

为什么我会收到错误消息?onupgradeneeded不应该只是更新版本号并重写对象(数据库)吗?

最佳答案

As far as I can tell, the problem is that I'm trying to recreate the same object with the same keypath

没错。虽然键路径与它无关,只是对象存储与现有对象存储同名。

isn't the new version making the script recreate the whole object?

没有。对象存储(以及索引和数据)在升级过程中保持不变,除非您在 onupgradeneeded 中手动删除它们。因此,为避免该错误,您应该检查 event.oldVersion,它在第一次创建数据库时为 0,随后为以前的版本号。 然后您可以仅在数据库首次初始化时创建您的对象存储,或者在升级时重新创建它之前将其删除。

更新:MDN 上的相关文档 IDBDatabase.createObjectStore这阐明了使用此调用如何需要唯一性。

The createObjectStore() method of the IDBDatabase interface creates and returns a new object store or index.

The method takes the name of the store as well as a parameter object that lets you define important optional properties. You can use the property to uniquely identify individual objects in the store. As the property is an identifier, it should be unique to every object, and every object should have that property.

关于indexeddb - 更新版本时 indexeddb 数据库出现约束错误,仅此而已,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17770716/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com