IndexedDB - Data provided to an operation does not meet requirements

Viewed 1123

I am trying to store data into an IndexedDB, but I am encountering a problem. When trying to add the well formatted JSON data I get the error:

DataError: Data provided to an operation does not meet requirements.

Below is my IndexedDB code:

function dbInit(key, value) {
    // Open (or create) the database
    var open = indexedDB.open("MyDatabase", 6);

    // Create the schema
    open.onupgradeneeded = function() {
        var db = open.result;
        var store = db.createObjectStore("MyObjectStore", {keyPath: "id", autoIncrement: true});
        var index = store.createIndex("types", "types");
    };

    open.onsuccess = function() {
        // Start a new transaction
        var db = open.result;
        var tx = db.transaction("MyObjectStore", "readwrite");
        var store = tx.objectStore("MyObjectStore");
        var index = store.index("types");


        // Add some data
        store.put(value);


        // Close the db when the transaction is done
        tx.oncomplete = function() {
            db.close();
        };
    }
}

After looking through some similar questions I have noticed that this issue is present if a keyPath is not specified, but below I have specified the keyPath to "id" and autoIncrement: true so this should act as the keyPath.

Below is the JSON data that I am trying to add - Passed into function under 'value' paramater. (Modified data as it is sensetitive, but in this format.)

[{
    "code": 1,
    "content": "XXX.html",
    "scheme": 4,
    "type": "XXX"
}, {
    "code": 2,
    "content": "XXX.html",
    "scheme": 6,
    "type": "XXX"
}, {
    "code": 3,
    "content": "XXX.html",
    "scheme": 1,
    "type": "XXX"
}, {
    "code": 4,
    "content": "XXX.html",
    "scheme": 4,
    "type": "XXX"
}]
1 Answers

Are you passing the value in as a string or parsed into an Array?

If a string, then the problem is that the generated key (c/o autoIncrement: true) can't be assigned to the value (c/o keyPath: "id") since you can't add properties to strings.

Simpler repro:

indexedDB.open('k').onupgradeneeded = e => {
  const db = e.target.result;
  const s = db.createObjectStore('s', {keyPath: 'id', autoIncrement: true}); 
  s.put('string');
};
Related