【发布时间】:2022-10-08 08:11:56
【问题描述】:
我试图创建一个 chrome 扩展,但我在更新我的数据库时遇到了一些问题。
在下面的代码中,我将index.get 用于包含某个值的对象。如果这样的对象不存在,我将创建一个新的,它工作得很好。
但是,如果数据库包含具有指定值的对象,我想将一个新对象附加到我搜索的对象内部的数组(allMessages)中。在这种情况下,细节并不重要。
重要的是找出我将这个新 obj 添加到数组(allMessages)的方式是否是更新数据库的有效方式。
records.forEach((person) => {
console.log("here1");
const index = objectStore.index("urlKeyValue");
let search = index.get(person.urlKeyValue);
search.onsuccess = function (event) {
if (search.result === undefined) {
// no record with that key
let request = objectStore.add(person);
request.onsuccess = function () {
console.log("Added: ", person);
};
} else {
// here im itterating an array that is inside the obj I searched for,
// and then checking if the key for that array matches **theUserId**
for (userObj of event.target.result.allMessages) {
if (theUserId == Object.keys(userObj)) {
// is this part correct. Is it possible to update the DB this way?
let objToAdd1 = {
time: person.allMessages[0][theUserId][0].time,
msg: person.allMessages[0][theUserId][0].msg,
};
let currentObj = userObj[theUserId];
let updatedObj = currentObj.push(objToAdd1);
}
}
)}
【问题讨论】:
-
你必须使用update
-
即使我将对象添加到已经存在的数组中,我也可以使用更新吗?而不是改变已经存在的变量的值?
-
你能证明我将如何在我的情况下使用
update吗? -
看起来数组是一条记录的一部分,这意味着您只能用新值覆盖整条记录,例如通过使用
put。从概念上讲,它是否在游标内都没有关系。
标签: javascript google-chrome-extension indexeddb