--- title: IDBObjectStore.keyPath slug: Web/API/IDBObjectStore/keyPath translation_of: Web/API/IDBObjectStore/keyPath ---
{{ APIRef("IndexedDB") }}
{{domxref("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就不知道要更新哪一条记录了。(译者注)
{{AvailableInWorkers}}
var mykeyPath = objectStore.keyPath;
任何类型。
在下面代码片段中,我们在数据库里打开了一个可读写的事务(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>'; }; };
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('IndexedDB', '#widl-IDBObjectStore-keyPath', 'keyPath')}} | {{Spec2('IndexedDB')}} | |
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-keypath", "keyPath")}} | {{Spec2("IndexedDB 2")}} |
{{Compat("api.IDBObjectStore.keyPath")}}