我正在尝试将数据存储到IndexedDB中,但是遇到问题。尝试添加格式正确的JSON数据时,出现错误:

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

以下是我的IndexedDB代码:
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();
        };
    }
}

在浏览了一些类似的问题之后,我注意到如果未指定keyPath,则会出现此问题,但是在下面,我将keyPath指定为“id”和autoIncrement:true,因此应将其用作keyPath。

以下是我要添加的JSON数据-传递到“值”参数下的函数中。 (修改后的数据虽然很敏感,但是采用这种格式。)
[{
    "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"
}]

最佳答案

您是以字符串形式传递值还是将其解析为数组?

如果是字符串,则问题在于无法将生成的键(c / o autoIncrement: true)分配给值(c / o keyPath: "id"),因为您无法向字符串添加属性。

更简单的复制:

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

关于javascript - IndexedDB-提供给操作的数据不符合要求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46486963/

10-12 17:35
查看更多