IDBObjectStore.keyPath
IDBObjectStore
的只读属性keyPath接口返回当前objectStore的key path。
什么是keyPath呢?在indexedDB中,一条记录就是一个object,object里面有一个属性作为这条记录的主要依据用来进行查询,而这个属性的属性名就是keyPath,属性值就是key。在用indexedDB的get方法时,提供key,而不需要指定keyPath,因为get方法把参数作为这个最主要的属性的值,在数据库中进行查询。(译者注)
如果该属性值为null,应用中必须在每一次进行修改性质的操作时提供一个key。
add、put方法都可以传第二个参数,当你当前的objectStore的autoIncrement为true时,你一般不会设置keyPath,如果这个时候你在put的时候不提供第二个参数,indexedDB就不知道要更新哪一条记录了。(译者注)
Note:
此特性在 Web Worker 中可用。句法
var mykeyPath = objectStore.keyPath;
Value
任何类型。
例子
在下面代码片段中,我们在数据库里打开了一个可读写的事务(transaction),并且用add()
向一个objectStore中添加了一些数据。在objectStore被创建之后,我们在console中打印了objectStore.keyPath的值。想查看完整的例子,请查看我们的To-do Notifications应用(查看在线例子)。
// Let us open our database
var DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = function(event) {
note.innerHTML += '<li>Database initialised.</li>';
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready to insert into the IDB
var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
// open a read/write db transaction, ready for adding the data
var transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of the transaction completing, when everything is done
transaction.oncomplete = function(event) {
note.innerHTML += '<li>Transaction completed.</li>';
};
transaction.onerror = function(event) {
note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
};
// create an object store on the transaction
var objectStore = transaction.objectStore("toDoList");
console.log(objectStore.keyPath);
// Make a request to add our newItem object to the object store
var objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = function(event) {
// report the success of our request
note.innerHTML += '<li>Request successful.</li>';
};
};
规范
规范 | 状态 | 备注 |
---|---|---|
Indexed Database API 2.0 keyPath |
Recommendation | |
Indexed Database API 2.0 keyPath |
Recommendation |
浏览器兼容性
BCD tables only load in the browser
相关内容
- 使用 IndexedDB
- 开始学习事务 transactions:
IDBDatabase
- 使用事务 transactions:
IDBTransaction
- 值域range的使用:
IDBKeyRange
- 检索、修改:
IDBObjectStore
- 使用游标:
IDBCursor
- 相关例子: To-do Notifications (view example live.)