javascript - Dexie.js 删除一个 id 不工作的项目

标签 javascript dexie

嗨,这是我的简单项目 js 代码示例

 const deleteOneNote = (id) => {
    const db = openNoteDb();
    db.notes.where('id').equals(id).delete();
  }

  $(document).on("click", ".remove_note", function () {
    
    const id = $(this).parent().parent().attr("id");
    const db = openNoteDb();
    db.notes.where('id').above(-1).modify(result => {
      if (result.id == id) {
        deleteOneNote(result.id);
        window.location.reload(true)
      }
    })
  })

但是我的删除功能不起作用我不明白请帮助我..

最佳答案

首先,您的函数 deleteOneNote() 必须从 db.transaction() 返回 promise ,这样您就可以等待删除完成。或者使函数异步并等待 db.transaction() 返回的 promise 。无论您选择什么,函数的调用者也必须在测试删除是否成功之前等待您的函数。

然后,我在代码上也看到了一个通病,就是Dexie实例是按需创建的,会导致内存泄漏,除非你在完成后关闭它。相反,在顶层声明 db,这样它就会在你的整个应用程序生命周期内存活,并让你的函数在任何地方都使用同一个 db 实例。

第三个常见错误(虽然可能不是这个原因)是人们在 key 存储为数字时提供字符串,反之亦然。确保提供给函数的 ID 与要删除的对象的类型不同。

// Declare one single Dexie instance in your entire application
// and use it from all functions.
const db = new Dexie("NotesDB");
// If you use modules, keep this code in a module and
// add an 'export' before 'const db = new Dexie("NotesDB");

db.version(1).stores({
  notes: `
  id,
  time,
  note,
  noteBackColor,
  noteTextColor,
  projectType,
  alarm`,
});

// Let you functions use the singleton Dexie instance:
const deleteOneNote = (id) => {
  return db.transaction('rw', db.notes, function () {
    // Note: Doing this in a transaction is over-kill, but ok.
    return db.notes.delete(id);
  }).catch((err) => {
    console.log(err);
    throw err; // Also, you probably want to rethrow the error...
  });
}

现在,这些是来自 Dexie's best-practices section 的代码建议并且不一定是您的代码无法删除项目的原因。

一个比较有意思的事情是:

  1. 数据库中您要删除的对象的“id”属性的值是多少?我假设您的对象看起来像{id: "x", time: "y", ...}

  2. 你传递给函数的参数是什么?如果您要删除的对象看起来像上一个项目符号中描述的那样,则 id 参数的值必须恰好是字符串“x”——不是对象,也不是数组或任何其他类型——一个带有精确值“x”。

此代码的工作测试是:

const foo = {id: "x", time: "y"};
db.notes.put(foo).then(async () => {
  if (await db.notes.get("x")) {
    console.log("My object is there!");
  } else {
    console.log("My object is not there!");
  }
  console.log("Now deleting it...");
  await deleteOneNote("x");
  if (await db.notes.get("x")) {
    console.log("My object is there!");
  } else {
    console.log("My object is not there!");
  }
}).catch(console.error);

运行这个测试的结果应该是:

My object is there!
Now deleting it...
My object is not there!

关于javascript - Dexie.js 删除一个 id 不工作的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71876224/

相关文章:

javascript - 原型(prototype)链,调用父方法的行为就像父构造函数从未运行过一样

javascript - 为什么 jquery-ui 对话框的高度总是设置为 auto?

javascript - 使用 Dexie 的本地存储不持久

javascript - 来自 Firefox 附加组件的内容脚本不会写入 IndexedDB

javascript - Vue.js - 数据更新时函数不执行

javascript - 如何在 Handlebars 模板中使用对象的括号表示法?

Javascript 哈希 (node.js)

javascript - 传递文档正文而不在网络 worker 中编辑它

javascript - mysql和IndexedDB之间的同步

javascript - 在 Dexie 迭代中使用 Promise