YDN 数据库 按 ID 删除记录 (索引数据库)

YDN DB Delete record by ID (IndexedDB)

本文关键字:数据库 索引 记录 删除 ID YDN      更新时间:2023-09-26

我正在使用YDN数据库进行索引数据库,我想使用其ID从对象存储中删除记录。这是我的架构:

var personsSchema = {
name: "persons",
keyPath: "id",
autoIncrement: true,
indexes: [{
    name: "id",
    unique: true
}, {
    name: "firstname",
    unique: false,
    multiEntry: false
}, {
    name: "lastname",
    unique: false,
    multiEntry: false
}]
};
schema = {
    stores: [personsSchema]
};
var db = new ydn.db.Storage("xdb", schema);

现在,我有删除记录的功能:

    function deleteEntry(id){
        var id = parseInt(id);
        var objectStore = "persons";
        var iterator = new ydn.db.ValueCursors(objectStore, "id", ydn.db.KeyRange.only(id));
        var mode = "readwrite";
        request = db.open(iterator, 1).then(function(cursor){
            cursor.clear();
        }, mode);
    }
这个

函数给了我这个错误:

Uncaught ydn.error.ArgumentException: Second argument must be cursor range iterator.

感谢您的回复。

它应该是:

function deleteEntry(id){
    var id = parseInt(id);
    var objectStore = "persons";
    var iterator = new ydn.db.IndexValueCursors(objectStore, "id", ydn.db.KeyRange.only(id));
    var mode = "readwrite";
    request = db.open(function(cursor){
        cursor.clear();
    }, iterator, mode).then(function() {
        console.log('cleared')
    });
}

但由于id是主键,因此不需要索引,它应该只是:

function deleteEntry(id){
    var id = parseInt(id, 10);
    var keys = db.remove("persons", id);
}

如果 id 不是主键,则以下代码的运行效率更高,因为它不会不必要地检索记录值。

function deleteEntry(id){
    var id = parseInt(id);
    var objectStore = "persons";
    db.keys(objectStore, "id", ydn.db.KeyRange.only(id)).done(function(keys) { 
      db.remove(objectStore, keys);
    };
}

我已经更正了 api 文档示例。