我一直在研究一个基于IndexedDB的项目,我注意到方法count()在Firefox上运行不正常。我不知道我是否缺少任何概念,因为我是新手,但我已经在Chrome和Opera上测试了它,它完美无缺。
代码的简化版本是:
var database;
var openDB = indexedDB.open("newDB", 1);
openDB.onupgradeneeded = function () {
database = openDB.result;
var newStore = database.createObjectStore("example", { keyPath: "id", autoIncrement: true });
newStore.createIndex("name", "name", { unique: false });
}
openDB.onsuccess = function () {
database = openDB.result;
var tx = database.transaction("example", "readwrite");
var store = tx.objectStore("example");
store.put({ name: "el_1" });
store.put({ name: "el_2" });
store.put({ name: "el_3" });
store.put({ name: "el_4" });
store.put({ name: "el_5" });
var transaction = database.transaction(['example'], 'readonly');
var objectStore = transaction.objectStore('example');
var counter = objectStore.index('name').count();
counter.onsuccess = function () {
total = counter.result;
console.log(total);
}
}
一切正常,除了属性结果在方法count(),返回0,而不是5.数据库被创建,对象存储在objectStore中。
我发现了问题。当我重写代码以在此处发布时,我首先更改了一些内容以使其更容易理解。问题是我的代码曾经是:
var createStore = database.createObjectStore("example", { keyPath: "id", autoIncrement: true });
createStore.createIndex("id", "id", { unique: true});
createStore.createIndex("name", "name", { unique: false });
接着:
var counter = objectStore.index('id').count();
我猜Chrome和Opera都没问题,但Firefox不允许这样做。 ^^