使用IndexedDB时,如何使用非关键索引删除多个记录?

时间:2015-02-20 18:06:50

标签: javascript indexeddb

我有代码在这里创建一个indexedDB:

function create_db() {
    var indexedDB = window.indexedDB || window.webkitIndexedDB || window.msIndexedDB;
    var request = indexedDB.open(“photos”, 2);

    request.onupgradeneeded = function(event) {
        var db = event.target.result;

        // Create photo db
        var photo_store = db.createObjectStore("photos", {keyPath: "photo_id"});
        var photo_id_index = photo_store.createIndex("by_photo_id",        "photo_id", {unique: true});
        var dest_id_index  = photo_store.createIndex("by_destination_id",  "destination_id");

        console.log(“store created”);
    };

    request.onsuccess = function(event) {
        console.log(“store opened”);
    };

    request.onerror = function(event) {
        console.log("error: " + event);
    };

}

我删除条目的代码:

 function remove_photos = function (destination_id, db) {
var transaction = db.transaction("photos", "readwrite");
var store       = transaction.objectStore("photos");
var index       = store.index("by_destination_id");
var request     = index.openCursor(IDBKeyRange.only(destination_id));

request.onsuccess = function() {
    var cursor = request.result;

    if (cursor) {
        cursor.delete();
        cursor.continue();
    }
};

}

如何使用by_destination_id索引删除记录,以便删除具有给定destination_id的所有记录,这是一个整数?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我找到了我的问题的解决方案,IDBKeyRange.only函数不像整数,它需要是一个字符串,所以用这行代替:

var request = index.openCursor(IDBKeyRange.only(destination_id.toString()));

使代码有效。