N
Nick
Guest
Nick Asks: Chrome Extension: How to get object from DB when searching by value?
Im trying to create a chrome extension, and have encountered an annoying problem. I have this function, where I add an object to my indexedDB if the
If the
Question: How to get an object from IndexedDB by a value?
This is how my objects are structured:
My Function where it all happens:
Im trying to create a chrome extension, and have encountered an annoying problem. I have this function, where I add an object to my indexedDB if the
urlKeyValue
of that object, does not already exist in the database.If the
urlKeyValue
does exist in the DB, i want to get the object in the DB that contains that value. This is where my problem begins. On line 184 - 188, i try to get the object by searching by the `urlKeyValue, but when I try to print the object, i get undefined.Question: How to get an object from IndexedDB by a value?
This is how my objects are structured:
Code:
{
message: "insert",
payload: [
{
urlKeyValue: "",
url: {
[userId]: {
[time]: {
msg: form_data.get("message"),
},
},
},
},
],
}
My Function where it all happens:
Code:
function insert_records(records, when) {
if (db) {
const insert_transaction = db.transaction(["roster2"], "readwrite");
const objectStore = insert_transaction.objectStore("roster2");
return new Promise((resolve, reject) => {
insert_transaction.oncomplete = function () {
console.log("ALL INSERT TRANSACTIONS COMPLETE.");
resolve(true);
};
insert_transaction.onerror = function () {
console.log("PROBLEM INSERTING RECORDS.");
resolve(false);
};
records.forEach((person) => {
// the "when" varieable isnt important, just disregard it
if (when != "init") {
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 {
const request2 = objectStore.get(person.urlKeyValue);
request2.onsuccess = function (event) {
console.log("--------" + event.target.result);
};
}
};
} else {
// this else statement isnt really important for this question
let request = objectStore.add(person);
request.onsuccess = function () {
console.log("Added: ", person);
//self.location.href;
};
}
});
});
}
}
SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.