IndexedDB - DataError: Data provided to an operation does not meet requirements

IndexedDB - DataError: Data provided to an operation does not meet requirements

我看过其他类似的问题。我的情况不同,因为我插入的是简单的 json 对象,没有键,没有自动递增。

这是执行插入的部分:

function insertInto(model, data, successCallback) {
    console.log("inserting into model "+model); 
    var transaction = db.transaction([model], IDBTransaction.READ_WRITE || 'readwrite');
    var store, i, request;
    var total = data.length;

    function successCallbackInner() {
        total = total - 1;
        if (total === 0) {
            successCallback();
        }
    }
    transaction.onerror = indexedDBError;
    store = transaction.objectStore(model);
    for (i in data) {
        if (data.hasOwnProperty(i)) {
            console.log(data[i]);
            request = store.add(data[i]);
            request.onsuccess = successCallbackInner;
            request.onerror = indexedDBError;
        }
    }
}

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

当我记录我尝试插入的数据时,它确认我的对象是一个具有三个字符串参数的简单对象:Object { cooked="well done", cheese="provolone", toasted="no"}

这里是 jsFiddle 完整的测试代码。

感谢任何和所有建议。甚至 "try this" 回复。从昨天早上开始我就一直在想办法解决这个问题。

谢谢

如果您在 Chrome 中尝试,您会看到一个信息更丰富的错误:

DataError: Failed to execute 'add' on 'IDBObjectStore': The object store uses out-of-line keys and has no key generator and the key parameter was not provided.

在 jsfiddle 中,您的对象存储是使用 db.createObjectStore(modelData[i].name, {autoIncrement: false}); 创建的,这意味着 (1) 没有关键路径(keyPath 选项不存在),并且 (2) 没有关键生成器(autoIncrement 选项为假)。这意味着 (1) 键不是从值中提取的,并且 (2) 商店不会为您生成键。所以你需要在调用 add() 时指定键,否则你会得到那个异常。

举几个例子:

// out-of-line keys, no key generator
var s1 = db.createObjectStore('s1');
s1.add(value, "my_key"); // key will be "my_key"

// out-of-line keys, key generator
var s2 = db.createObjectStore('s2', {autoIncrement: true});
s2.add(value); // key will be 1
s2.add(value, 123); // key will be 123
s2.add(value); // key will be 124

// in-line keys, no key generator
var s3 = db.createObjectStore('s3', {keyPath: 'id'});
s3.add({id: 123}); // key will be 123

// in-line keys, key generator
var s4 = db.createObjectStore('s4', {keyPath: 'id', autoIncrement: true});
s4.add({}); // key will be 1 (and inserted into record)
s4.add({id: 123}); // key will be 123
s4.add({}); // key will be 124 (and inserted into record)

未显示的案例将引发 DataError 异常。