如何只有没有值的键或如何将不同的值或放入 IndexedDb 中?

How to have only the key with no value or how to put distinct values or into IndexedDb?

我需要将 不同 的字符串放入 IndexedDb 中。我可以将它们作为没有值的键(对 indexedDb 来说还很新,所以甚至不知道这是否可能)。现在的问题是,每次读取这些字符串时,它们都会重复放入 IndexDb 中。不想编写另一种方法来检查这些值是否已经存在,以保持方法的可重用性。我相信应该有一种方法可以重写 upgradeDb.createObjectStore('categories', { autoIncrement: true }); 来做到这一点,只是找不到方法。我的代码:

使用 table 创建数据库:

function idbOpen() {
    return idb.open('greedy', 1, upgradeDb => {
        upgradeDb.createObjectStore('categories', { autoIncrement: true });
    });
}

写入数据库:

putArrayToDb = (tableName, arrayToPut) => {
    if (this.dbPromise) {
        this.dbPromise.then(db => {
            if (!db) return;

            var tx = db.transaction(tableName, 'readwrite');
            var store = tx.objectStore(tableName);
            arrayToPut.map(arrayItem => {
                store.put(arrayItem);
            });
        })
    }
}

putArrayToDb('categories', ["value1", "value2", "value3"]);

提前致谢。

由于您想使用字符串作为键,autoIncrement 不是您想要的 - 它会为您生成键。

定义对象存储时删除autoIncrement选项,并简单地使用显式键和虚拟值(例如true):

var DUMMY_VALUE = true;

arrayToPut.map(arrayItem => {
    store.put(/*value=*/DUMMY_VALUE, /*key=*/arrayItem);
});