user4623666
user4623666

Reputation:

Index on array keypath doesn't find any values

I want to get familiar with indexedDB to built my Firefox WebExtension.

My sample data is structured like this:

const sampleDataRaw = [ 
      {
      "ent_seq" : 1413190,
      "att1" : [ {
        "sub11" : "content1",
        "sub12" : [ "word" ]
      }, {
        "sub11" : "content2"
      } ],
      "att2" : [ {
        "sub21" : "other content",
        "sub22" : [ "term" ]
      } ]
    }, {
      "ent_seq" : 1000010,
      "att2" : [ {
        "sub21" : "more content"
      }, {
        "sub22" : "more words"
      } ]
    }
    ] // end sampleRawData

I got as far as opening/creating my database, adding this sample data and querying it by the ent_seq key using objectStore.get() and objectStore.openCursor().

The problem arises when I want to search the sub11 or sub21 fields using indexes I should have created for these like this:

objectStore.createIndex("sub11Elements", "att1.sub11", { unique: false });
objectStore.createIndex("sub21Elements", "att2.sub21", { unique: false });

When I want to search, say, fields sub11 as here:

var index = objectStore.index("sub11Elements");
index.get("content1").onsuccess = function(event) {
        // I should have the first object of my data now, alas the result is undefined instead
     };

It certainly does succeed, but the returned value is undefined since the get() didn't actually find anything.

I want to know why it doesn't find the entry and how to make it find it. I figured it might be because the keypath is wrong, but as stated, if I instead search by the key (ent_seq) I can successfully get the result.att1[i].sub11 values.

On mozilla's websites it's stated that keys can be of type string and array (or array within array etc) amongst others, and keypath parts are supposed to be concatenated using dots. From searching on stackexchange I've so far found that it's not possible to have variable keys inside the keypath, but that shouldn't be the case here anyway.
Therefore, I really don't see what might be causing the search to not find the object inside the database.

Upvotes: 2

Views: 137

Answers (1)

Josh
Josh

Reputation: 18690

  1. It looks like the second level of objects are arrays, not properties of the first level of objects. The . accessor accesses sub properties, not indices of an array.
  2. IDBObjectStore.prototype.get always yields success when there is no error, and is not indicative of whether a match was found.

A bit more on point 1. Look at "att1":[{"sub11" : "content1","sub12" : [ "word" ]}.... Pretend this was was an actual basic JavaScript object. Would you be able to use att1.sub11? No. Because the value of att1 is an array, not an object.

Upvotes: 2

Related Questions