【问题标题】:Javascript: How to update IndexedDB?Javascript:如何更新 IndexedDB?
【发布时间】:2022-10-08 08:11:56
【问题描述】:

我试图创建一个 chrome 扩展,但我在更新我的数据库时遇到了一些问题。

在下面的代码中,我将index.get 用于包含某个值的对象。如果这样的对象不存在,我将创建一个新的,它工作得很好。

但是,如果数据库包含具有指定值的对象,我想将一个新对象附加到我搜索的对象内部的数组(allMessages)中。在这种情况下,细节并不重要。

重要的是找出我将这个新 obj 添加到数组(allMessages)的方式是否是更新数据库的有效方式。

records.forEach((person) => {
  console.log("here1");
  const index = objectStore.index("urlKeyValue");
  let search = index.get(person.urlKeyValue);

  search.onsuccess = function (event) {
    if (search.result === undefined) {
      // no record with that key
      let request = objectStore.add(person);

      request.onsuccess = function () {
        console.log("Added: ", person);
      };
    } else {

// here im itterating an array that is inside the obj I searched for, 
// and then checking if the key for that array matches **theUserId**
      for (userObj of event.target.result.allMessages) {
        if (theUserId == Object.keys(userObj)) {

// is this part correct. Is it possible to update the DB this way?
          let objToAdd1 = {
            time: person.allMessages[0][theUserId][0].time,
            msg: person.allMessages[0][theUserId][0].msg,
          };

          let currentObj = userObj[theUserId];
          let updatedObj = currentObj.push(objToAdd1);
        }
      }
)}

【问题讨论】:

  • 你必须使用update
  • 即使我将对象添加到已经存在的数组中,我也可以使用更新吗?而不是改变已经存在的变量的值?
  • 你能证明我将如何在我的情况下使用update 吗?
  • 看起来数组是一条记录的一部分,这意味着您只能用新值覆盖整条记录,例如通过使用put。从概念上讲,它是否在游标内都没有关系。

标签: javascript google-chrome-extension indexeddb


【解决方案1】:

使用objectStore.openCursor您只能更新部分记录。
以下仅更新图书价格。

  const transaction = db.transaction("books", "readwrite");
  const objectStore = transaction.objectStore("books");
  records = [{ id: "kimetu", price: 600 }];

  records.forEach((book) => {
    const index = objectStore.index("id");
    const search = index.get(book.id);
    search.onsuccess = () => {
      if (search.result === undefined) {
        const request = objectStore.add(book);
        request.onsuccess = () => {
          console.log("Added: ", book);
        };
      } else {
        const request = objectStore.openCursor(IDBKeyRange.only(book.id));
        request.onsuccess = () => {
          const cursor = request.result;
          if (cursor) {
            cursor.value.price = 1000;
            const updateRequest = cursor.update(cursor.value);
            updateRequest.onsuccess = () => {
              console.log("Updated: ", cursor.value.price);
            };
            cursor.continue();
          }
        };
      }
    }
  });

【讨论】:

    猜你喜欢
    • 2015-02-26
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多