Filtering Browser Equipment Notes by Department | Dexie.js

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This ArticleThis article was created using an automated generation workflow leveraging generative AI. We verified the Dexie.js 4.0.11 schema and search API, the storage scope and limitations of IndexedDB, and the licenses against official documentation, cross-referencing them with the tutorial code and explanations.

Verification Status: 🧪 Official specifications and code statically verified / GitHub Pages rendering and browser operations unverifiedWe verified the consistency of the demo HTML, common JavaScript, README, input values, and search logic, as well as the JavaScript syntax. We have not yet opened the public demo in a browser to perform actual operations such as IndexedDB searching or reloading.

Filtering Browser Equipment Notes by Department | Dexie.js

When filtering an equipment list by department name, one approach is to iterate over an array in JavaScript each time. However, as the number of records increases or if you want data to persist after closing the application, an in-browser database becomes useful.

This tutorial uses Dexie.js to make IndexedDB easier to handle. We register two dummy devices and search by changing the department name. We then trace why the same results are returned even after reloading. This is intended for beginners who want to learn how to handle local data in the browser.

Live Demo: Searching Equipment by Changing Department Name

Fixed Demo HTML, Common JavaScript, and Tutorial README

What is Operated and What is Returned

Input FieldExpected ResultKey Observation Point
総務(Initial Value)Terminal A with id 1The input and the department value match exactly
経理Terminal B with id 2Changing the condition changes the returned records
営業[]Zero results do not indicate a search failure; rather, no matching rows were found.
総務(Trailing space)[]For exact string matches, extra spaces are treated as distinct values.

The data used here is [{ id: 1, department: "総務", name: "端末A" }, { id: 2, department: "経理", name: "端末B" }]. Do not input actual data such as employee names or asset numbers.

First, change the search criteria

  1. Open the demo above and click "Execute". The initial value of the input field is 総務.

  2. Verify that the results panel displays Terminal A, where the ID is 1 and the department is General Affairs.

  3. Change the input field to 経理 and click "Execute" again. The display switches to Terminal B.

  4. 営業 change to . Because no terminals match, the result is an empty array [].

  5. 総務 Add a trailing space such as . Verify that even if they look similar on the screen, they do not match.

  6. After successfully searching for General Affairs, reload the page and click "Execute" again. In an environment where the data registered initially remains, the same Terminal A is returned.

Initial data is registered only on the first search. Simply opening the demo does not create the database; it is designed to add two entries to IndexedDB after "Execute" is clicked. If browser site data is cleared or storage is unavailable, the initial registration process runs again.

The expected value is a small, fixable sample. You cannot compare search speeds with only two entries. Rather than concluding that "it is always fast because it is an indexed search," observe how criteria are passed to the IndexedDB index and how data is persisted within the browser.

The diagram illustrates the conceptual relationships, while the implementation uses a single store.

The instructional material includes an ER diagram representing the relationship between departments and terminals. This diagram illustrates the business relationship where multiple terminals belong to a single department. However, the database created by the demo does not include a department table.itemsin a single object store named department and have it hold a string. I want to prevent misinterpreting the diagram as a direct physical database structure.

erDiagram
    DEPARTMENT ||--o{ EQUIPMENT : "所属"
    EQUIPMENT {
      int id PK
      string department
      string name
    }

The DEPARTMENT in the diagram represents a business concept, while the items in the code represents the actual storage location. This is not instructional material for learning how to normalize department names into a separate table.Mermaid ER diagram notation is a notation for representing entities and relationships, and it is not a feature that automatically creates tables in a database.

Dexie.js makes IndexedDB easier to read

IndexedDB is an object database provided by the browser. It is suitable for handling structured records and indexes rather than saving string keys and values like Web Storage. Because the IndexedDB API directly handles events and transactions, the code tends to become lengthy.Dexie.js wraps this API, allowing it to be written using table schemas and Promise-based operations.

async function findByDepartment(value) {
  const { default: Dexie } = await import("https://esm.sh/dexie@4.0.11");
  const db = new Dexie("DailyCodeInventory");
  db.version(1).stores({ items: "id,department" });

  try {
    if (await db.items.count() === 0) {
      await db.items.bulkPut([
        { id: 1, department: "総務", name: "端末A" },
        { id: 2, department: "経理", name: "端末B" }
      ]);
    }
    const rows = await db.items
      .where("department")
      .equals(value)
      .toArray();
    console.log(rows);
    return rows;
  } finally {
    db.close();
  }
}

findByDepartment("総務");

This is an example extracting only the necessary lines of the demo processing. In the implementation, lib() is loaded through a common dexie@4.0.11 function, and displayed in the results section using say(). Just like the code snippet excerpt, it performs initial data insertion, searching via the department index, and finally closes the connection.

db.version(1).stores({ items: "id,department" })Here, the first item, id, serves as the primary key, and the subsequent department, serves as the search index. In Dexie's schema notation, ++id means auto-incrementing, but this demo does not include ++. Therefore, IDs are explicitly specified in the sample data. The description of ++id previously found in the README contradicted the implementation, so it was corrected to id this time.

Records entering the object store are identified by their primary key.count() asynchronously checks the current count. Because it registers two records using bulkPut() only when there are zero records, the same samples are not rewritten on every search.bulkPut() bulk-puts an array of records. The behavior of replacing existing identical primary keys isTable.put(), but in this tutorial, it is only called when empty.

The subsequent where("department") specifies the index registered in the schema as the search target.equals(value) creates the value match condition, and toArray() retrieves the results as an array. The demo calls try...finally in db.close(). This ensures that the database connection is cleaned up even if an exception occurs during the search.

Exact match and partial match are different searches

equals() checks for an exact value match. Official Dexie.js documentation states that string comparisons are case-sensitive. Therefore, 総務 and 総務 are different keys, and総務部 does not match 総務. Since empty input also matches the condition to find an empty string, it basically returns [].

If partial match search is required, define the requirements first. For example, if "department name starts with 総", consider other writing methods such as startsWith(), and if "contains characters in the middle", consider filter(). However, under conditions that do not use indexes, all records may be read before filtering, and the load varies depending on the amount of data.where()The keys that can be passed to must be created indexes or primary keys.

Indexes are not magic that makes everything fast. It is a mechanism where search items are registered in the schema, and indexes are also maintained when saved data is updated. The more indexes you add, the greater the burden on storage space and update processing. Design by narrowing down to frequently searched items. When there is a large number of records, judge after measuring with actual record counts, devices, and search conditions.

Separating errors and results

Observed behaviorPossible causeNext step to check
Output is []No matching department name, or spaces or capitalization differdepartmentCompare actual data of and input values character by character
Results do not change after "Run"JavaScript or Dexie CDN could not be loadedCheck network connection and browser developer tools console
Data disappeared after reloadSite data deletion, private mode, and storage quota limitsRun again with the same origin in normal mode
where("department")Fails inThe schema index name and query name do not matchstores()Check the declaration of, the existing database version, and the console errors
file://Does not work inBrowsers may not be able to use IndexedDB for local filesOpen via GitHub Pages or a localhost HTTP server

If search results return zero, do not delete or initialize the database first. Check input whitespace, schema names, and whether the page shares the same origin in that order. Browsers separate storage areas by website origin. Different domains, different ports, and http versus https cannot connect to the same database. The demo Pages and local localhost are separate storage areas.

IndexedDB is not a shared ledger

The data in this learning material is stored in that browser and site origin. Although it is local processing that is not sent to a server, it does not mean it is a 'secure safe because it is stored.' Code executed with the same origin can access stored data, and data may be lost due to site data deletion or browser storage management. Default storage in IndexedDB is best-effort, and capacity and deletion conditions vary by browser. For details, refer to MDNBasic concepts of IndexedDBandStorage capacity and eviction conditionsPlease refer to. A mechanism for synchronizing across all devices is not included.

In production, it can be used for offline catalogs, partially completed forms, and temporary caches retrieved from servers. To synchronize shared inventory across multiple devices, separately design the server-side source of truth, authentication, conflict resolution, backup, and handling of synchronization failures. Do not use the in-browser database alone as the source of truth for shared data.

Do not enter actual employee names, device serial numbers, asset ledgers, or customer information into this demo or test environment. Because this educational material fetches external libraries from a CDN, use it in an environment that permits external network connections. Dexie.js 4.0.11 is specified as Apache-2.0 in the officialpackage.jsonand with the same tagLICENSEcan also be verified. Diagram rendering Mermaid 11.12.2official ER diagram guidein addition toMIT license for the relevant tagcan be referenced. License verification and permission and storage rules for handling actual data are separate items to check.

Conclusion

Passing the department name input to equals()retrieves matching records through the index. Comparing the results of changing the input, adding whitespace, and reloading reveals the characteristics of exact match search and in-browser storage.

Small samples are intended for understanding the mechanism. When using with actual data, consider the reasons for indexing search fields, DB version upgrades, cross-device sharing, and data deletion and backup separately before implementation.

Verification Method

The tutorial's JavaScript syntax, HTML elements and settings, article input values, operation names, expected results, and README implementation descriptions were statically verified. Demo page rendering, CDN loading, writing to IndexedDB, department search, and post-reload behavior have not been verified in a browser.

Document information

Article title
Filtering Browser Equipment Notes by Department | Dexie.js
Published
Updated
Source
https://papanda925.com/?p=19018&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL