Google News
logo
JavaScript IndexedDB - Interview Questions
Can you perform join operations in IndexedDB like SQL?
No, IndexedDB doesn't support join operations like SQL. However, you can manually implement relationships by storing keys from one object store in another and using separate requests to fetch related data.

Code Example :

Sure, here's a simple example of how you might manually implement relationships in IndexedDB:

Suppose you have two object stores, authors and books. Each book object has an authorId field, which is the key of the author in the authors object store.
let db; // Assuming db is the opened IndexedDB database

// Get the transaction
let transaction = db.transaction(["books", "authors"]);

// Get the object stores
let bookStore = transaction.objectStore("books");
let authorStore = transaction.objectStore("authors");

// Let's find the details of the book and its author with bookId=1
let bookId = 1;

// Request to get the book
let bookRequest = bookStore.get(bookId);

bookRequest.onsuccess = function(e) {
  let book = e.target.result;
  console.log("Book: ", book.title);

  // Request to get the author using the authorId from the book
  let authorRequest = authorStore.get(book.authorId);

  authorRequest.onsuccess = function(e) {
    let author = e.target.result;
    console.log("Author: ", author.name);
  };

  authorRequest.onerror = function(e) {
    console.error("Error fetching author: ", e.target.error);
  };
};

bookRequest.onerror = function(e) {
  console.error("Error fetching book: ", e.target.error);
};?

This code gets a book and its corresponding author from the database. First, it fetches the book from the "books" object store. Then, using the authorId from the book, it fetches the author from the "authors" object store. This simulates a join operation.
Advertisement