"Locate and retrieve data using find and findOne methods in indexed

Even though indexedDB lacks findOne or find functions like MongoDB, my goal is to achieve a similar functionality. I have a data store in indexedDB with an index created on the stop_id.

The objective is to retrieve all documents in the store that contain a specific stop_id. It's possible for multiple objects to share the same stop_id.

My Current Implementation:

I'm attempting a workaround method (feel free to suggest improvements)

// This function gets called from HTML using AngularJS
$scope.findOne = function(stop_id) {
    var db;
    var request = indexedDB.open("Trans");
    request.onerror = function(event) {
        alert("Could not establish connection to Database");
    };
    request.onsuccess = function(event) {
        db = event.target.result;
        var objectStore = db.transaction("times").objectStore("times");
        var index = objectStore.index("stop_id");

        var range = IDBKeyRange.only(stop_id);

        // Need to add code here to retrieve
        // either one or all documents with the stop_id provided from the HTML
    }
}

To utilize this function in the HTML:

<div class="medium-6 columns" ng-repeat="stops in objects | orderBy: 'stop_name'">
    <div class="card hoverable">
        <div class="content">
            <span class="title">{{stops.stop_name}}</span><small class="float-right">{{stops.stop_id}}</small>
            <!-- The following function will search another object store and retrieve all documents matching the stop_id -->
            {{ findOne(stops.stop_id)}}</p>
        </div>
    </div>
</div> 

I am exploring this approach because indexedDB does not support joins by default, and I intend to use native workarounds of indexedDB to fetch additional data related to an id in another datastore dynamically. Performance is not a major concern as both data stores are expected to have less than 150 items each.

Answer №1

Implement the IDBIndex get method or openCursor method in your code.

// example for single object
var range = IDBKeyRange.only(myId);
var getRequest = index.get(range);
getRequest.onsuccess = function(event) {
  var result = event.target.result;
  console.log(result);
};

// for multiple objects ...
var getRequest = index.openCursor(range);
var documentsFound = [];
getRequest.onsuccess = function(event) {
  var request = event.target;
  var cursor = request.result;

  if(!cursor) {
    console.log('no match found, or no more matches found');
    someFunction(documentsFound);
  } else {
    console.log('Found:', cursor.value);
    documentsFound.push(cursor.value);
    cursor.advance();
  }
};

If there can be multiple objects with the same stop_id in the database, ensure that you don't set the unique:true flag when creating the index in your onupgradeneeded handler.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JavaScript code in Three.js is experiencing issues when running in a secure HTTPS environment

After transitioning my website from http to https, I encountered an issue with one of my projects. The background using the Three.js library in this random generator does not show up when the URL is https. However, when the URL is http, the generator wor ...

How to retrieve a response from a vanilla JavaScript AJAX request using the POST method

Here is a PHP function that I created to save data: case "start_question": $user_id = "123"; $p_id = $_POST[""]; $question_id = $_POST["question_Id"]; $answer = $_POST["answer_String"]; $counter = $_POST["counter"]; $points = $_PO ...

Dealing with hurdles in user interface while refreshing ng-repeat information

Indeed, it seems that creating a long grid with numerous rows using Angular is possible. However, issues arise when it comes to updating the data. Rendering all 10,000 rows in the grid initially works, although it may take a few seconds. The challenge lie ...

Extrude a face in Three.js along its respective normal vector

My goal is to extrude faces from a THREE.Geometry object, and my step-by-step approach involves: - Specifying the faces to be extruded - Extracting vertices on the outer edges - Creating a THREE.Shape with these vertices - Extruding the shape using THREE.E ...

Guide to utilizing keyup function in ckeditor

I'm currently utilizing AngularJS for my development work. Setting up the CK Editor in my controller: function initEditor(){ CKEDITOR.replace( 'editor1', { on: { pluginsLoaded: function( evt ) { ...

Problem with Bootstrap Datepicker click functionality

I am currently utilizing the bootstrap datepicker along with bootstrap-rtl. The problem I encountered was that I had two fields, one for the date and one for the name. The datepicker would not appear until I clicked on the date input first, then on the na ...

Is it possible to utilize an angular 1 template in conjunction with angular 2?

I am currently working on developing a real-time reactive admin dashboard for a Dashboard/POS system. While I primarily work with Java and have experience with .net, I have recently started practicing with the MEAN stack for creating real-time web applicat ...

Inject objects into external JavaScript using script tag

Out of pure curiosity, I am wondering if there is a specific method for passing data (possibly a JavaScript object) to an external JavaScript file within the script tag that imports it. <script type="text/javascript" src="example.js"> {example:&apos ...

I am encountering an issue where my JavaScript code is not being executed on my HTML page as expected. I

I have implemented an accordion using Bootstrap 4 accordion, card, and collapse classes in my HTML page with success. However, I am facing a challenge with maintaining the state of the accordion when navigating away from and then returning to the page. By ...

The process of sending parameters to an API in ReactJS: a guide

My objective is to target .....the values originating from login (can be anything)-> for example email:'[email protected]' password:'12345678' I am required to extract the username until "@" and use it as a username i ...

Node.js tutorial: Packing 2D boxes efficiently

Working on a web application using node js and in need of a box packing algorithm to determine the optimal solution. While I could attempt to create an algorithm from scratch (view http://en.wikipedia.org/wiki/Packing_problems), I'm curious if a simil ...

Jade: modify the text box input to show = " ..."

I am new to Jade and Html, and I am currently working on creating a form in Jade. The issue I am facing involves a simple text box that looks like this: input(type='text', name='sessionID', value = 'valueID') Whenever I want ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

Utilizing a window.onload function in Microsoft Edge

After trying to run some code post-loading and rendering on the target page, I was recommended to use the Window.load function. This method worked flawlessly in Firefox and Chrome, but unfortunately, I couldn't get it to function in IE. Is there an al ...

What is the best way to pass `response` data between routes in Express when setting up PayPal subscriptions?

I'm currently in the process of integrating PayPal subscriptions into my Node.js application using Express. I've come across a challenge when trying to pass the subscription ID obtained from PayPal's /create-subscription route to the /execut ...

Is the HTML Accordion Panel set to be open by default?

I recently found this amazing animated accordion menu on the W3 Schools website and I really appreciate its design. However, I am struggling to figure out how to set a specific section to be open and "active" by default. Visit the original page here I at ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

Differences between class and prototype Array.isArray

Throughout my coding journey, I've often heard the saying "Classes are just syntactic sugar for prototypes." However, an interesting example challenges this notion. function SubArray() {} SubArray.prototype = new Array( ); console.log(Array.isArray( ...

What is the best approach for managing caching effectively?

My SPA application is built using Websocket, Polymer, ES6, and HTML5. It is hosted on a Jetty 9 backend bundled as a runnable JAR with all resources inside. I want to implement a feature where upon deploying a new version of the JAR, I can send a message ...

AngularJS: Retrieving the sequence of choices in md-select with multiple selections

After choosing two options in the <md-select>, I am presented with an array of those two values. However, my query lies in how to determine the order in which these selections were made. As demonstrated in this codepen example, if I choose One first ...