我已经看到多个JavaScript示例使用createIndex
在ObjectStore创建后直接定义ObjectStore索引:
var objectStore = ixDb.createObjectStore(osName, { keyPath: pkName, autoIncrement: autoIncrement });
objectStore.createIndex("name", "name", { unique: false });
有人可以告诉我如何在不调用createIndex
的情况下在预先存在的桌子上使用createObjectStore
吗?我想这里真正的问题是如何在不使用createObjectStore
的情况下获取对objectStore的引用?
我尝试了以下几种变体而没有运气:
var objectStore = window.IDBTransaction.objectStore(ObjectStoreName);
var index = objectStore.createIndex(ixName, fieldName, { unique: unique, multiEntry: multiEntry });
答案 0 :(得分:4)
你在onupgradeneeded
期间这样做,它应该与你首先制作对象存储的地方相同。在那里,您可以执行升级所需的任何操作,例如创建新索引。 Here is an example.
答案 1 :(得分:3)
Chrome目前不支持onupgradeneeded事件。如果您想使用旧的或新的W3规范获得对ObjectStore的引用,这是使用旧的setVersion命令或通过新的onupgradeneeded事件通过onsuccess事件的一种可能的解决方法:
var ixDb;
var ixDbRequest;
var ixDbVersionTansaction;
//Check to see if we have a browser that supports IndexedDB
if (window.indexedDB) {
ixDbRequest = window.indexedDB.open(dbName, dbVersion);
//For browsers like chrome that support the old set version method
ixDbRequest.onsuccess = function (e) {
ixDb = ixDbRequest.result || e.result;
if (typeof ixDb.setVersion === "function") {
//Put your version checking logic here
if (oldVersion < newVersion) {
var verRequest = ixDb.setVersion(newVersion);
verRequest.onerror = function (e) {
//handling error logic here
}
verRequest.onsuccess = function (e) {
//Get a reference to the version transaction
//from the old setVersion method.
ixDbVersionTansaction = verRequest.result;
//Create database using function provided by the user.
UserFunction();
}
}
}
};
ixDbRequest.onupgradeneeded = function (e) {
//FF uses this event to fire the transaction for upgrades.
//All browsers will eventually use this method. Per - W3C Working Draft 24 May 2012
ixDb = ixDbRequest.result || e.currentTarget.result;
//Get a reference to the version transaction via the onupgradeneeded event (e)
ixDbVersionTansaction = e.currentTarget.transaction;
//Create database using function provided by the user.
UserFunction();
};
UserFunction(){
//ObjectStore is accessed via ixDbVersionTansaction variable
// in either instance (transaction..objectStore("ObjectStoreName"))
var ObjectStore = ixDbVersionTansaction.objectStore("ObjectStoreName");
var index = ObjectStore.createIndex("ixName", "fieldName");
}