Indexeddb 搜索具有特定字段的所有订单

Indexeddb search all orders with a particular field

我到处都看了又看,但事实证明 IndexedDb 并不是很有名。我有一个名为 orders 的对象库,它带有一个自动生成的键,每个订单的结构如下:

{"dealername":"something","dealerid":num,"totalbill":num,"items":[{},{}]}

现在由于 objectstore 订单可以有多个具有相同 dealerid 的订单,我如何才能获得具有特定 dealerid 的所有订单?

抱歉,我有一个 SQL 背景。 谢谢

  1. 在 dealerid 上创建索引。
  2. 在 dealerid 索引上打开游标并迭代。

这里有一些非常简单的代码可以帮助您入门:

function onUpgradeNeeded(event) {
  var db = event.target.result;

  var orderStore = db.createObjectStore('orders', ...);

  // Create the index on dealerid here
  orderStore.createIndex('dealeridindex', 'dealerid');
}

function queryOrdersByDealerID(db, id, onOrder, onComplete) {
  var tx = db.transaction('orders');
  tx.onComplete = onComplete;
  var orders = tx.objectStore('orders');
  var index = orders.index('dealeridindex');
  var request = index.openCursor(id);
  // You could also do this, if you wanted, it is identical:
  // var request = index.openCursor(IDBKeyRange.only(id));

  request.onsuccess = function(event) {
    var cursor = event.target.result;
    if(!cursor) return;
    onOrder(cursor.value);
    cursor.continue();
  };
}

// Now to use it:
var openRequest = indexedDB.open('dbname', version);

// Attach our upgrade handler that gets called when higher version found
openRequest.onupgradeneeded = onUpgradeNeeded;

// Now do a query
openRequest.onsuccess = function(event) {
  // event.target === openRequest === this
  // use whatever you prefer, e.g. this.result or openRequest.result
  var openDatabaseConnection = event.target.result;

  var someId = 5;

  function handleOrder(order){
    console.log('Order %o', order);
  }

  function whenAllMatchingOrdersIterated(event) {
    console.log('Finished iterating over orders');
  }

  // 'execute' the query
  queryOrdersByDealerID(openDatabaseConnection, someId,
    handleOrder, whenAllMatchingOrdersIterated);
}