我正在开发一个网站,该网站将从表单中获取用户数据并将其显示在下表中。我正在使用 indexedDB,一切都可以在我的笔记本电脑上本地运行,但是当我将其部署到 GitHub 页面时,出现以下错误: NotFoundError:无法在“IDBDatabase”上执行“事务”:找不到指定的对象存储之一。
let db;
let request = window.indexedDB.open("newDatabase", 1);
request.onupgradeneeded = function (event) {var db = event.target.result;
var objectStore = db.createObjectStore("client", {autoIncrement: true,});
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("lastName", "lastName", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
objectStore.createIndex("ID", "ID", { unique: true });
objectStore.createIndex("postal", "postal", { unique: false });
objectStore.createIndex("phoneNumber", "phoneNumber", { unique: true });
var formElements = document.getElementById("form");
var request = db
.transaction(["client"], 'readwrite')
.objectStore("client")
.add({
name: formElements[0].value,
lastName: formElements[1].value,
email: formElements[2].value,
postal: formElements[3].value,
ID: formElements[4].value,
phoneNumber: formElements[5].value,
});
我在网上看到,当objectStore的名称与事务中的名称不同时,可能会发生这种情况,但这里不是这种情况,它们都是相同的。我尝试将它们更改为其他名称,但问题仍然存在......
db.createObjectStore("client", {autoIncrement: true,});
.
.
.
var request = db
.transaction(["client"], 'readwrite')
问题出在
request.onupgradeneeded
回调中,在我的实现中,我添加到 objectStore
两个具有 相同 ID 的客户端。正如您在下面的代码中所看到的,ID 应该是唯一的。通过添加这两个客户端,该函数会抛出错误并调用 request.onerror
,这就是无法打开数据库且未创建 objectStore 的原因。
request.onupgradeneeded = function (event) {
var db = event.target.result;
console.log("Object Store creation");
var objectstore = db.createObjectStore("client", {
autoIncrement: true,
});
objectstore.createIndex("name", "name", { unique: false });
objectstore.createIndex("lastName", "lastName", { unique: false });
objectstore.createIndex("email", "email", { unique: true});
objectstore.createIndex("ID", "ID", { unique: true }); //HERE WAS THE PROBLEM
objectstore.createIndex("postal", "postal", { unique: false });
objectstore.createIndex("phoneNumber", "phoneNumber", { unique: true});
for (var i in clientData) {
objectstore.add(clientData[i]); // Here was the error thrown
}
};
const clientData = [
{
name: "Piotr",
lastName: "Wesoly",
email: "[email protected]",
ID: 'CCU238293', //The same ID as in the other client
postal: "90-234",
phoneNumber: "500500200"
},
{
name: "Pawel",
lastName: "Rosiak",
email: "[email protected]",
ID: 'CCU238293', //The same ID as in the other client
postal: "93-234",
phoneNumber: "500400200"
},
];
解决方法很简单:将 unique 设置为 false 或将其中一个客户端的 ID更改为唯一的 ID。