gpt4 book ai didi

javascript - 获取对象存储已经存在于 onupgradeneeded 中

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:57 26 4
gpt4 key购买 nike

我的代码如下(通常是众所周知的对象的命名约定):

var DBOpenRequest = window.indexedDB.open("messages", 6);
//...
DBOpenRequest.onupgradeneeded = function(event) {
console.log("Need to upgrade.");
var db = event.target.result;
console.log(db);

db.onerror = function(event) {
console.log("Error upgrading.");
};

// Create an objectStore for this database
var objectStore = db.createObjectStore("messages", { keyPath: "id", autoIncrement: true });
};

这对于版本 3 和 4 运行良好。当涉及到版本 5 时,我得到错误:

Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists. at IDBOpenDBRequest.DBOpenRequest.onupgradeneeded

createObjectStore 不是在新版本的空数据库上运行吗?如何修复错误?

我碰巧记录了 db 对象,详细信息如下:

enter image description here

我很好奇为什么摘要行中的版本号和展开时的版本号不同。

最佳答案

Isn't the createObjectStore operating on a new version of the database which is empty?

当您得到 upgradeneeded 时,数据库处于您之前保留它的任何状态。由于您不知道用户会访问您的代码的哪个版本,因此您需要查看事件的 oldVersion 以找出那是什么。典型的模式是这样的:

var rq = indexedDB.open('db', 5);
rq.onupgradeneeded = function(e) {
var db = rq.result;
if (e.oldVersion < 1) {
// do initial schema creation
db.createObjectStore('users');
}
if (e.oldVersion < 2) {
// do 1->2 upgrade
var s = db.createObjectStore('better_users');
s.createIndex('some_index', ...);
db.deleteObjectStore('users'); // migrating data would be better
}
if (e.oldVersion < 3) {
// do 2->3 upgrade
rq.transaction.objectStore('better_users').createIndex('index2', ...);
}
if (e.oldVersion < 4) {
// do 3->4 upgrade
db.createObjectStore('messages', ...);
}
if (e.oldVersion < 5) {
// do 4->5 upgrade
// ...
}
}

I am curious why the version number is different in the summary line and when expanded.

那个很微妙...我相信在记录 5 时数据库已经开始升级。但是because an exception was thrown in the upgradeneeded handler the upgrade was aborted , 和 the version number was rolled back在记录详细信息之前到 4

关于javascript - 获取对象存储已经存在于 onupgradeneeded 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002460/

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