在 indexeddb 中插入重复值

Inserting duplicate value in indexeddb

当我在我的数据库中插入时,它插入相同的数据两次。

Table 创建

var oOptions = {
    keyPath: account.primaryKey,
    autoIncrement: true
};
var oStore = dbHandle.createObjectStore(account.tableName, oOptions);

var oIxOptions = {
    unique: false
};
account.fields.forEach(function(item) {
    oStore.createIndex(item + "Index", item, oIxOptions);
});

插入

var defered = $q.defer();
try {
    var objectStore = config.database.transaction(tableName, "readwrite").objectStore(tableName);
    var result = objectStore.add(entity);
    result.onerror = function(e) {
        defered.reject("Can't insert into account");
        throw e;
    }
    result.onsuccess = function(e) {
        defered.resolve();
    }
} catch (e) {
    defered.reject("Can't insert into account");
    throw e;
}
return defered.promise;

检索

var defered = $q.defer();
try {
    var req = $window.indexedDB.open(config.databaseName, 1.0);
    req.onsuccess = function(evt) {
        config.database = evt.target.result;
        var transaction = config.database.transaction(account.tableName, IDBTransaction.READ_ONLY);
        var objectStore = transaction.objectStore(account.tableName);
        var tmpData = [];
        objectStore.openCursor().onsuccess = function(event) {
            var cursor = event.target.result;
            if (!cursor) {
                defered.resolve(tmpData);
                return;
            }
            tmpData.push(cursor.value);
            cursor.continue();
        };
    }
} catch (e) {
    defered.reject("Can't pull from account");
    throw e;
}
return defered.promise;

有什么建议吗??

这可能不是 indexedDB 的问题,而是您使用 try/catch 和 promises 的问题。您是否在没有 try/catch 且没有承诺的情况下进行了测试?您在这里使用承诺的理由是什么?考虑到您不需要 try/catch 并且不需要承诺来执行这些简单的任务。