jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.2k stars 348 forks source link

cannot delete particular data in store using IDBKeyRange and cursor. #290

Closed huisso97 closed 1 year ago

huisso97 commented 1 year ago

I am connect IndexedDB like README code.

const db = await openDB(name, version, {
  upgrade(db, oldVersion, newVersion, transaction, event) {
    // …
  },
  blocked(currentVersion, blockedVersion, event) {
    // …
  },
  blocking(currentVersion, blockedVersion, event) {
    // …
  },
  terminated() {
    // …
  },
});

Then, I insert data into store named "test" with key which is date. I recognize that too many stored data cause browser loading to be longer, so I decided to delete some old data in store, iterating the store using cursor. And the next code is what I try. I intended to delete data of particular past time using IDBKeyRange, but all of data is deleted, not the bondary what i set.

  const db: IDBPDatabase<DBConfig> = await connectDB();
  const range = IDBKeyRange.lowerBound(new Date(Date.now() - 100000000));

  try {
    const tx = db.transaction("test", "readwrite");
    let cursor = await tx.store.openCursor(range);
    while (cursor) {
      console.log(cursor.key, cursor.value);
      cursor.delete();
      cursor = await cursor.continue();
    }

So, I want to know how to delete some range of data. Thank you for your replying.

jakearchibald commented 1 year ago

I think you're wanting to set an upper bound, not a lower bound.

jakearchibald commented 1 year ago

(closing because it isn't an issue with this library. It's a general IDB question. But, I'm happy to continue helping)

huisso97 commented 1 year ago

thank you for replying !!

jakearchibald commented 1 year ago

No problem. You can also pass your range object straight to .delete():

const db: IDBPDatabase<DBConfig> = await connectDB();
const range = IDBKeyRange.upperBound(new Date(Date.now() - 100000000));
await db.delete("test", range);

All of this assumes that the keys in your store are dates. You haven't shown your schema so I don't know that for sure.