我有一个带有表单,姓氏,姓氏,电子邮件和矩形的表。我必须在矩形中插入一个带有时间表的数组的数组等。我创建了一个带有表单,姓氏,姓氏和电子邮件的客户,将它们添加到索引eddb中,以后加载它们以插入矩形阵列。之后,我想将newobjectstore
放在索引edDB中,其中电子邮件与我选择/插入的客户相同。但是使用此代码,我的数组将放置在具有自己ID的新对象存储中。
function cmd_SaveRec(hypeDocument, elementID)
{
hypeDocument.getElementById('rectext').innerHTML = hypeDocument.getElementById('beschriftung').value;
var store_cust = db.transaction(["customer"], "readwrite").objectStore("customer").index("rectangle");
var cursorReq = store_cust.openCursor();
cursorReq.onsuccess = function (e) {
cursor = e.target.result;
if(cursor) {
if(cursor.value.email == mailAdd)
{
//cursor.update([rec_ar]);
if(store_cust.objectStore.put({rectangle: [rec_ar]}))
{
console.info(store_cust.objectStore);
console.info('Gespeichert');
alert("Gespeichert");
} else {
console.info('cmd_SaveRec::Problem');
}
}
cursor.continue();
}
};
cursorReq.onerror = function(e) {
console.log("Error");
console.dir(e);
}
}
var store_cust = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME_CUSTOMER, { keyPath: 'cust_id', autoIncrement: true });
store_cust.createIndex('form', 'form', { unique: false }); //
store_cust.createIndex('surname', 'surname', { unique: false });
store_cust.createIndex('lastname', 'lastname', { unique: false });
store_cust.createIndex('email', 'email', { unique: true });
store_cust.createIndex('rectangle', 'rectangle', { unique: false, multiEntry: true });
简短答案
- 在
objectStor.put(data, key)
或
中提供标识符/键作为第二个参数 - 使用文档中所述的IDBCursor und Und更新
解释
如文档中所述:
iDbobject store接口的put((方法在数据库中更新给定记录,或者如果给定项目尚不存在,则插入新记录。(Source Developer.mozilla.org(
您使用的方法objectStore.put()
用于插入或更新任务。如果我正确,您正在寻找 update - cursor.update()
是您的朋友(您发表评论(。 - 这是这里的首选方法!
,但是您可以使用这两种方法来做到这一点。说您想更新,但是如果记录不存在,则创建一个。在这种情况下,引擎必须知道您的记录是否存在以及您尝试更新的记录。
如果您的objectStore
使用自动启动主键记录的标识符不在record 本身中,因此您必须将ID作为put()
的第二个参数提供功能。
我发现自己照顾ID会更容易。然后,ID是记录的一部分(可在您在ObjectStore-Creation上提供的keypath
下找到(。然后
示例
// create a store with ids YOU handle e.g.
var request = indexedDB.open(dbname, dbversion+1);
request.onerror = errorHandler;
request.onupgradeneeded = function(event){
var nextDB = request.result;
if (!nextDB.objectStoreNames.contains('account')) {
nextDB.createObjectStore('account', {keyPath: "id", autoIncrement: true});
}
}
// Your record has to llok like this
{id: 123456789, rectangle: [rec_ar]}
// Now your code above should work
如果您的DB中有一个主键:
store_cust.objectStore.put({rectangle: [rec_ar]}, PRIMARY_KEY)
// where PRIMARY_KEY is the id of this specific record
顺便说一句
不要使用if -else检查事务的完成 - 它是asynchronus-如果/else每次都在这里 - 如上所述,请使用回调(onsuccess
(。/p>
您应该阅读我的引用文档。Mozilla是IndexedDB内容的伟大Ressource。