javascriptbrowserindexeddbdexie

How to delete a key/value inside value field with Dexie.js?


I have a row with value like this below:

{
   "id": 1,
   "token": "abcd"
}

How do I delete and save the value without "token" so it becomes this?

{
   "id": 1
}

Do I need to first get the object, modify it then save back?


Solution

  • Maybe this will help you:

    function patch(db, id, delta) {
      return new Promise((resolve, reject) => {
        const tx = db.transaction('mystore', 'readwrite');
        tx.onerror = (event) => reject(event.target.error);
        tx.oncomplete = () => resolve();
        const store = tx.objectStore('mystore');
        const request = store.get(id);
        request.onsuccess = (event) => {
          const object = event.target.result;
    
          if (!object) {
            reject(new Error(`No matching object for ${id}`));
            return;
          }
    
          for (const prop in delta) {
             if (typeof delta[prop] === 'undefined') {
               delete object[prop];
             } else {
               object[prop] = delta[prop];
             }
          }
    
          store.put(object);
        };
      });
    }
    
    async function dostuff() {
      let db;
      const id = 1;
      const delta = {
        token: undefined
      };
    
      try {
        db = await connect();
        await patch(db, id, delta);
      } finally {
        if (db) {
          db.close();
        }
      }
    }