javascriptindexeddb

IndexedDB error: IDBObjectStore Symbol could not be cloned


I have a class where some properties shouldn't be stored to the indexedDB store. It works when I clone the object and remove the properties afterwards, however that solution I didn't like so much. I wondered if there is a solution where we just set a property somehow private, so when writing to the indexedDB store the property shouldn't be included.

I tried the following: I used a symbol in my class for a property and through get/set I modify the property, however when I try to store the object to the indexedDB store I get the following error: IndexedDB error: IDBObjectStore Symbol could not be cloned

Here is an example code:

var request = indexedDB.open('test', 2);

request.onerror = function(event) {
    // Handle errors.
};
request.onupgradeneeded = function(event) {
    var db = event.target.result;

    // Create an objectStore to hold information about our customers. We're
    // going to use "ssn" as our key path because it's guaranteed to be
    // unique.
    var objectStore = db.createObjectStore("customers", {
        keyPath: 'id'
    });

    var mystring = "Hello World"
    
    var myblob = new Blob([mystring], {
        type: 'text/plain'
    });
    var file = new File([myblob], 'test');

    var a = Symbol('a');
    var obj = {
        id: 'foo',
        b: a
    };
    obj[a] = file;
    objectStore.add(obj);

};

Solution

  • Objects that can be stored in IndexedDB must be serializable. The spec definition for this is:

    https://html.spec.whatwg.org/multipage/structured-data.html#serializable-objects

    Symbol values are explicitly called out in the algorithm steps as non-serializable.

    You could exclude the property from serialization by making it non-enumerable, e.g.:

    Object.defineProperty(obj, 'b', {value: a, enumerable: false});