indexedDB highest keypath

后端 未结 2 1214
不思量自难忘°
不思量自难忘° 2021-01-23 13:50

I have a database inside indexedDB filled using an Emberjs adapter. I have set the keypath like this:

this.addModel(App.Device, { keyPath: \'key\' });

相关标签:
2条回答
  • 2021-01-23 14:13

    Use objectStore.openKeyCursor with the direction "prev":

    const openCursorRequest = store.openKeyCursor(null, 'prev')
    openCursorRequest.onsuccess = () => {
      const cursor = openCursorRequest.result
      const maxKey = cursor && cursor.key
      // use maxKey...
    }
    

    Using Promise:

    const getMaxKey = (db, storeName) => new Promise((resolve, reject) => {
      const tx = db.transaction(storeName, 'readonly')
      const store = tx.objectStore(storeName)
      const openCursorRequest = store.openKeyCursor(null, 'prev')
      openCursorRequest.onsuccess = () => {
        const cursor = openCursorRequest.result
        resolve(cursor && cursor.key)
      }
      openCursorRequest.onerror = () => {
        reject(openCursorRequest.error)
      }
    })
    
    0 讨论(0)
  • 2021-01-23 14:26

    Here's an IDB pattern for the last entry:

    1. Bind your cursor value to the first ID entry. ("0" should do it since keys are lexicographically ordered.) (Original answer linked to question https://stackoverflow.com/a/22812410/317937 which has now been removed)
    2. Use a reverse cursor ("prev" or "prevunique" direction depending on your needs)
    3. Your next entry will be the last entry (skip() or continue() either should work)
    0 讨论(0)
提交回复
热议问题