indexeddb objectstore.add() keypath = 'id'

Rya*_*ers 1 javascript key add indexeddb

我有几个对象存储,并在它们之间拆分。在 chrome 扩展的初始安装期间,我将数据添加到各种对象存储中,我想确保数据正确对齐。所以当安装过程中出现不同步时。“keypath / id”将正确匹配。没什么大不了的。

初始安装后出现问题。并添加另一条记录。初始记录的“id”/keyPath/key 显示 id:1、id:2、id:3 等...

但在初始安装后记录。在将密钥添加到对象库之前,我不再知道密钥是什么。是否有我遗漏的代码片段,以便我可以创建一个对象并添加到 objecstore,以增加 id,或者我是否搞砸了最初创建 id: 1 并且应该使用类似 keyPath: 1 或 key: 1 或 Primarykey 之类的东西:1?

我可以花很长时间来解决它,并使用一些承诺,并且

objectstore.add(object)
.then(objecstore.get(event.key) 
.then(objestore.put(key, {"id":key}) 
Run Code Online (Sandbox Code Playgroud)

我确实注意到上面的正确承诺代码。但是 objectstore.add,然后在添加后获取密钥,然后 .put({"id": key}) 更新“id”就完成了,就是它的要点。我首先试图阻止需要这样做。

有点像 SQL 这样的数据库,并且有 2 个主键,它们是数字、自动递增,并且在同一个表的各个方面都完全相同。但就我而言,密钥更新,“id”占用空间。并且不确定如何从最初的开始中删除“id”。或者一旦完成,如何在没有一堆额外的废话承诺的情况下保持密钥和“id”同步。

在下面的代码中注释,试图弄清楚。并且我自己还没有弄清楚

objectstore.add(object)
.then(objecstore.get(event.key) 
.then(objestore.put(key, {"id":key}) 
Run Code Online (Sandbox Code Playgroud)
    const ms_master = [{
//========================
//did i mess up here in creating id: and should of used like keypath:1?
//========================
      "id": 1,
      "baseurl": "www.example1.net",
      "prefix": "ex1",
      "name": "tryout1",
    }, {
      "id": 2,
      "baseurl": "www.something.com",
      "prefix": "so",
      "name": "some some",
    }, {
      "id": 3,
      "baseurl": "woops.org",
      "prefix": "woo",
      "name": "arghs",
    }]

    var db;
    var request = window.indexedDB.open("mystyle", 1);
    request.onerror = function(event) {
      console.log("error: ")
    };
    request.onsuccess = function(event) {
      db = event.target.result;
      console.log("success: " + db);
    };
    request.onupgradeneeded = function(event) {
        var db = event.target.result;
        if (!db.objectStoreNames.contains("ms_master")) {
//========================
//did i mess up here in creating the store?
//========================
          var objectStore = db.createObjectStore("ms_master", {
            keypath: "id",
            autoIncrement: true,
            unique: true
          });
          objectStore.createIndex("baseurl", "baseurl", {
            unique: false
          });
          objectStore.createIndex("prefix", "prefix", {
            unique: false
          });
          objectStore.createIndex("name", "name", {
            unique: false
          });
//========================
//seems to make no difference
//========================
          //objectStore.createIndex("id","id", { unique: true });
          for (var i in ms_master) {
            objectStore.add(ms_master[i]);
          }
//========================
//once added, should i do a objecstore.get and grab data, then do a objectstore.put that does not have 'id" in it?
//========================
        }

        $(document).ready(function() {
              document.getElementById('ms_table_add').addEventListener("click", ms_table_add);
            }

            function ms_table_add() {
              var db;
              var request = indexedDB.open('mystyle', 1);
              request.onsuccess = function(e) {
                db = e.target.result;
                var transaction = db.transaction('ms_master', "readwrite");
                var objectStore = transaction.objectStore('ms_master');
                var myobj = [
                  "id",
                  "name",
                  "prefix",
                  "baseurl"
                ];
                var myarray = {};
                for (var h = 0; h < myobj.length; h++) {
                  if (h == 0) {
//========================
//am i not getting the correct code to get id and keypath to sync up?
//========================
                    //{name: 'ms_master', keyPath: 'id'}
                    //myarray[myobj[h]] = 'id';
                  } else {
                    var temp = document.getElementById('ms_table_add_' + myobj[h]).value;
                    if (typeof temp !== "undefined" && temp !== null && temp !== "") {
                      myarray[myobj[h]] = temp;
                    }
                  }
                }
                objectStore.add(myarray);
//==============================
//trying to avoid extra promises to add, then get key, then update id here.
//==============================

                document.getElementById("ms_listings_master_add").innerHTML = "";
              }
            }

            function site_adding() {
              //function that builds up a html form / textareas / inputs and .innerhtml into 
              //<div id="ms_listings_master_add"></div>
            }
Run Code Online (Sandbox Code Playgroud)

Jos*_*ell 7

您同时使用两个功能 - 内嵌密钥和密钥生成器。我将分别解释它们,然后它们是如何组成的。

内联和外联键

内联键的键值出现在记录本身中 - 具有 keyPath 的存储使用内联键。相比之下,外联键具有单独的键值。

var storeWithOutOfLineKeys = db.createObjectStore('s1');
storeWithOutOfLineKeys.put({name: 'alice'}, 1);

var storeWithInLineKeys = db.createObjectStore('s2', {keyPath: 'id'});
storeWithInLineKeys.put({name: 'bob', id: 1});
Run Code Online (Sandbox Code Playgroud)

如果您没有为具有外联键的存储提供显式键,则调用put()add()将失败。如果您确实向带有内联键的存储提供了显式键,则调用put()add()将失败,如果记录不包含内联键值(例如,缺少上例中的属性),则调用将失败id

密钥生成器

当您指定时,autoIncrement: true您使用的是规范所称的密钥生成器。对于添加的每条记录,如果没有另外指定,则第一个将 get 1,第二个2等。您可以通过查看put()oradd()请求的结果来找出使用了什么键,例如

var request = store.put({name: 'alice'});
request.onsuccess = function() {
  console.log('put got generated key: ' + request.result;
};
Run Code Online (Sandbox Code Playgroud)

内嵌密钥和密钥生成器

使用密钥生成器时,其行为add()put()变化:

密钥生成器和外链密钥:调用add()or时不需要传递显式密钥put();如果省略,则使用生成的密钥:

var storeWithOutOfLineKeys = db.createObjectStore('s1', {autoIncrement: true});
storeWithOutOfLineKeys.put({name: 'alice'});
Run Code Online (Sandbox Code Playgroud)

如果传递了一个显式密钥,它将被使用,要么覆盖以前的记录,要么添加一个新的记录。(如果传递的键恰好是一个大于生成器值的数字,则生成器将设置为该数字。)

密钥生成器和内联密钥:调用add()or时无需在记录中指定密钥put();如果省略,则将生成的键注入到值中。

var storeWithInLineKeys = db.createObjectStore('s2', {keyPath: 'id', autoIncrement: true});
storeWithInLineKeys.put({name: 'bob'}).onsuccess = function(e) {
  var id = e.target.result;
  storeWithInLineKeys.get(id).onsuccess = function(e) {
    console.log(JSON.stringify(e.target.result));
    // {"name": "bob", "id": 1}
  });
});
Run Code Online (Sandbox Code Playgroud)

同样,如果记录确实包含一个键值,它将被使用。(如果它是一个高于密钥生成器状态的数字,则将调整密钥生成器。)

我相信最后一种情况与您的代码正在执行的操作相匹配 - 内联密钥和密钥生成器。您可以使用add()put()requests的结果来确定添加的键,并通过在记录中显式指定键来更新记录:

storeWithInLineKeys.put({name: 'eve', id: 1}); // overwrites old #1
Run Code Online (Sandbox Code Playgroud)