Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在IndexedDB中创建具有多个条件的查询_Javascript_Indexeddb - Fatal编程技术网

Javascript 如何在IndexedDB中创建具有多个条件的查询

Javascript 如何在IndexedDB中创建具有多个条件的查询,javascript,indexeddb,Javascript,Indexeddb,我有一个包含多个要查询的索引的存储。在本例中,假设我有一个带有user\u id索引和create\u date(时间戳)的消息存储(假设我有索引-user\u id/create\u date/user\u id,create\u date) 我知道如何按id查询用户: var range = IDBKeyRange.only('123'); store.index('user_id').openCursor(range).onsuccess= function(e){....}; 我知道如

我有一个包含多个要查询的索引的存储。在本例中,假设我有一个带有user\u id索引和create\u date(时间戳)的消息存储(假设我有索引-user\u id/create\u date/user\u id,create\u date)

我知道如何按id查询用户:

var range = IDBKeyRange.only('123');
store.index('user_id').openCursor(range).onsuccess= function(e){....};
我知道如何按日期查询:

var range = IDBKeyRange.lowerBound(Date.now()-24 * 60 * 1000))
store.index('create_data').openCursor(range).onsuccess = function(e){....};
我不知道如何同时查询两者。我知道我可以使用JS解析这两个函数的结果,但我想知道是否可以使用IDB来完成这项工作


编辑-我想做的伪查询是

user_id=123 AND create_date < (NOW() - 24 * 60 * 1000)
user\u id=123并创建日期<(现在()-24*60*1000)

谢谢!

答案是使用
IDBKeyRange.bound

var range = IDBKeyRange.bound(['123'],['123', Date.now()-10*1000]);

store.index('user_id,create_date').getCursor(range).onsuccess = function(e){...}

基本上,所有IDBKeyRange范围都可以使用
绑定范围来表示,因此通过使用多个值,我们可以创建我们想要的任何复合范围下面是一个工作示例

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Stackoverflow</title>
    <script type="text/javascript" charset="utf-8">
            var db_handler = null;
            var dbDeleteRequest = window.indexedDB.deleteDatabase("toDoList");
            dbDeleteRequest.onerror = function(event) {
                console.log("Error while deleting database.", true);
            };

            dbDeleteRequest.onsuccess = function(event) {
                // Let us open our database
                var DBOpenRequest = window.indexedDB.open("toDoList", 5);

                DBOpenRequest.onsuccess = function(event) {
                  console.log('<li>Database initialised.</li>');

                  // store the result of opening the database in the db variable. This is used a lot below
                  db_handler = DBOpenRequest.result;

                  // Run the addData() function to add the data to the database
                  addData();
                };

                DBOpenRequest.onupgradeneeded = function(event) {
                  console.log('<li>DBOpenRequest.onupgradeneeded</li>');
                  var db = event.target.result;

                  db.onerror = function(event) {
                    console.log('<li>Error loading database.</li>');
                  };

                  // Create an objectStore for this database   //, { keyPath: "taskTitle" });  { autoIncrement : true }
                  var objectStore = db.createObjectStore("toDoList", { autoIncrement : true });

                  // define what data items the objectStore will contain

                  objectStore.createIndex("user_id", "user_id", { unique: false });
                  objectStore.createIndex("create_data", "create_data", { unique: false });
                  objectStore.createIndex("tags",['user_id','create_data'], {unique:false});
                };
            };

            function addData() {
              // Create a new object ready to insert into the IDB
              var newItem = [];
              newItem.push({ user_id: "101", create_data: (1000)});
              newItem.push({ user_id: "102", create_data: (Date.now() - 18 * 60 * 1000)});
              newItem.push({ user_id: "103", create_data: (Date.now() - 18 * 60 * 1000)});
              newItem.push({ user_id: "101", create_data: (2000)});
              newItem.push({ user_id: "101", create_data: (989)});
              newItem.push({ user_id: "104", create_data: (Date.now() - 18 * 60 * 1000)});

              console.log(newItem);

              // open a read/write db transaction, ready for adding the data
              var transaction = db_handler.transaction(["toDoList"], "readwrite");

              // report on the success of opening the transaction
              transaction.oncomplete = function(event) {
                console.log('<li>Transaction completed: database modification finished.</li>' + new Date());
              };


              transaction.onerror = function(event) {
                console.log('<li>Transaction not opened due to error. Duplicate items not allowed.</li>');
              };

              // create an object store on the transaction
              var objectStore = transaction.objectStore("toDoList");

              addData2(transaction, objectStore, newItem, 0, true);

            };

            function addData2(txn, store, records, i, commitT) {
              try {
                if (i < records.length) {
                  var rec = records[i];
                  var req = store.add(rec);
                  req.onsuccess = function(ev) {
                    i++;
                    console.log("Adding record " + i + " " + new Date());
                    addData2(txn, store, records, i, commitT);
                    return;
                  }
                  req.onerror = function(ev) {
                    console.log("Failed to add record." + "  Error: " + ev.message);
                  }
                } else if (i == records.length) {
                  console.log('Finished adding ' + records.length + " records");
                }
              } catch (e) {
                console.log(e.message);
              }
              //console.log("#########")
            };


            function select() {
                var transaction = db_handler.transaction('toDoList','readonly');
                var store = transaction.objectStore('toDoList');
                var index = store.index('tags');

                var range = IDBKeyRange.bound(['101', 999],['101', 2001]);

                var req = index.openCursor(range);

                req.onsuccess = function(e){
                    var cursor = e.target.result;
                        if (cursor) {
                            if(cursor.value != null && cursor.value != undefined){
                                console.log(cursor.value);
                             }
                            cursor["continue"]();
                        }
                }
            }
    </script>
</head>
<body>
    <div id="selectButton">
        <button onclick="select()">Select Data</button>
        <input type="text" id="selectData" value="">
    </div>
</body>
</html>

栈溢出
var db_handler=null;
var dbDeleteRequest=window.indexedDB.deleteDatabase(“toDoList”);
dbDeleteRequest.onerror=函数(事件){
log(“删除数据库时出错。”,true);
};
dbDeleteRequest.onsuccess=函数(事件){
//让我们打开数据库
var DBOpenRequest=window.indexedDB.open(“toDoList”,5);
DBOpenRequest.onsuccess=函数(事件){
console.log(“
  • 数据库已初始化。
  • ”); //将打开数据库的结果存储在db变量中 db_handler=DBOpenRequest.result; //运行addData()函数将数据添加到数据库 addData(); }; DBOpenRequest.onupgradeneeded=函数(事件){ log(“
  • DBOpenRequest.onupgradeneeded
  • ”); var db=event.target.result; db.onerror=函数(事件){ log(“
  • 加载数据库时出错。
  • ”); }; //为此数据库创建一个objectStore/,{keyPath:“tasktile”};{autoIncrement:true} var objectStore=db.createObjectStore(“toDoList”,{autoIncrement:true}); //定义objectStore将包含哪些数据项 createIndex(“user\u id”,“user\u id”,{unique:false}); createIndex(“create_data”,“create_data”,{unique:false}); createIndex(“标记”,“用户id”,“创建数据”],{unique:false}); }; }; 函数addData(){ //创建一个新对象,准备插入IDB var newItem=[]; push({user_id:“101”,create_data:(1000)}); push({user_id:“102”,创建_数据:(Date.now()-18*60*1000)}); push({user_id:“103”,创建_数据:(Date.now()-18*60*1000)}); push({user_id:“101”,create_data:(2000)}); push({user_id:“101”,create_data:(989)}); push({user_id:“104”,创建_数据:(Date.now()-18*60*1000)}); console.log(newItem); //打开读/写db事务,准备添加数据 var transaction=db_handler.transaction([“toDoList”],“readwrite”); //关于交易成功的报告 transaction.oncomplete=函数(事件){ console.log('
  • 事务完成:数据库修改完成。
  • '+新日期()); }; transaction.onerror=函数(事件){ console.log(“
  • 事务由于错误而未打开。不允许重复项。
  • ”); }; //在事务上创建对象存储 var objectStore=transaction.objectStore(“toDoList”); addData2(事务,objectStore,newItem,0,true); }; 函数addData2(txn、存储、记录、i、提交){ 试一试{ 如果(i<记录长度){ var rec=记录[i]; var req=存储添加(rec); req.onsuccess=功能(ev){ i++; log(“添加记录”+i+“”+new Date()); addData2(txn、存储、记录、i、提交); 返回; } req.onerror=功能(ev){ console.log(“添加记录失败。”+”错误:“+ev.message”); } }else if(i==records.length){ console.log('完成添加'+records.length+“records”); } }捕获(e){ 控制台日志(e.message); } //控制台日志(“#############”) }; 函数选择(){ var transaction=db_handler.transaction('toDoList','readonly'); var store=transaction.objectStore('toDoList'); var index=store.index('tags'); var range=IDBKeyRange.bound(['101',999],'101',2001]); var req=索引。openCursor(范围); req.onsuccess=功能(e){ var cursor=e.target.result; 如果(光标){ if(cursor.value!=null&&cursor.value!=未定义){ console.log(cursor.value); } 游标[“继续”](); } } } 选择数据
    关键点和概念解决方案