2

I am using indexedDB, and I have a orderProductIndex index inside the order_items collection. The index is not unique!

What I want to do is, select every record from the index with a specific id, and update their timestamp value. I can update one record easily, but I can't the others.

First I was try to get all records, iterate them manually and update them one by one, but this don't work, 0 element was updated.

index.getAll([order_id, product_id]).onsuccess = (event) => {
    $.each(event.target.result, function (index, item) {
        item.timestamp = Date.now();
        objectStore.put(item).onsuccess = function (event) {
            console.log('item updated')
            console.log(event.target.result)
            resolve();
        }
    });
    resolve();
}

Second attempt was the iterate them through with a cursor and use the cursor's update method, so far this was the best approach, this updates only one element, if there were multiple elements it seems like a get in an endless loop, end never get logged out,

let index = objectStore.index("orderProductIndex");

let keyRange = IDBKeyRange.only([order_id, product_id]);

let request = index.openCursor(keyRange);

request.onsuccess = function (event) {
    console.log('cursor opened');

    let cursor = event.target.result;

    if (cursor) {
        let record = cursor.value;

        record.timestamp = Date.now();

        console.log(record);

        let request = cursor.update(record);

        cursor.continue();

    }
    else {
        console.log('end')
        resolve();
    }
}

So now I replace the cursor.continue() with resolve() and one element always gets updated successfully, any idea what I am doing wrong? Any help would be appreciated.

Telexx
  • 420
  • 2
  • 11
  • Your code actually looks fine to me (with the continue() call). I tried it locally with what I infer your database's schema was like, and it worked just fine. So something else must be going on. Can you share your code that creates the database and starts the transaction? Also, consider logging `cursor.primaryKey` on each iteration. Also, it might help to handle errors both on the index.openCursor() request and the cursor.update() - e.g. `request.onerror = e => reject(e.target.error);` or log or something. There's also a chance you're hitting a browser bug - which browser are you using? – Joshua Bell Jul 11 '23 at 22:52
  • Please provide more information in your question in order to receive help – Josh Jul 19 '23 at 13:55

0 Answers0