2017-01-09 71 views
0

如何獲得沒有特定字段的對象?

function setup() { 
 
\t myRequest = indexedDB.deleteDatabase('myDatabase') 
 
\t myRequest.onsuccess \t = function() { 
 
\t \t var myRequest 
 
\t \t 
 
\t \t myRequest = indexedDB.open('myDatabase') 
 
\t \t myRequest.onupgradeneeded = function(response) { 
 
\t \t \t var myDatabase 
 
\t \t \t \t ,myObjectStore 
 
\t \t \t 
 
\t \t \t myDatabase = response.target.result 
 
\t \t \t myObjectStore = myDatabase.createObjectStore('myData',{autoIncrement:true}) 
 
\t \t \t myObjectStore.createIndex('myIndex', 'field2') 
 
\t \t } 
 
\t \t myRequest.onerror = function(response) { 
 
\t \t \t debugger 
 
\t \t } 
 
\t \t myRequest.onsuccess = function(response) { 
 
\t \t \t var myTransaction 
 
\t \t \t \t ,myObjectStore 
 
\t \t \t \t ,myRequest 
 
\t \t \t \t ,obj = {} 
 
\t \t \t window.myDatabase = response.target.result 
 
\t \t \t myTransaction = myDatabase.transaction(['myData'],'readwrite') 
 
\t \t \t myObjectStore = myTransaction.objectStore('myData') 
 
\t \t \t obj.field1 = 'a' 
 
\t \t \t obj.field2 = 'b' 
 
\t \t \t myObjectStore.add(obj) 
 
\t \t \t obj = {} 
 
\t \t \t obj.field1 = 'c' 
 
\t \t \t myObjectStore.add(obj) 
 
\t \t } 
 
\t } 
 
} 
 
setup() 
 

 
function myFunction() { 
 
\t var myTransaction = myDatabase.transaction(['myData']) 
 
\t var myObjectStore = myTransaction.objectStore('myData') 
 
\t var myIndex = myObjectStore.index('myIndex') 
 
\t // The following line is where I need help: 
 
\t var myRange = IDBKeyRange.only(null) 
 
\t // I'm trying to get the objects where field2 doesn't exist. 
 
\t var myRequest = myIndex.openCursor(myRange) 
 
\t myRequest.onsuccess = function(response) { 
 
\t \t result = response.target.result 
 
\t \t if (result) { 
 
\t \t \t console.log(result) 
 
\t \t \t result.continue() 
 
\t \t } 
 
\t } 
 
\t 
 
} 
 
</script>
<a href="javaScript:myFunction();">click here</a>

回答

2

不能以簡單的方式做到這一點。沒有辦法查詢丟失/空白字段。

但是,你可以很聰明並且解決這個問題。

  1. 在對象存儲中存儲對象之前,檢查對象的屬性是否爲空(null/undefined /空字符串/ etc)。如果該字段丟失,請將一個單獨的字段(如「otherPropertyIsMissing」)設置爲一個值。我建議使用空字符串('')或0.如果屬性不丟失,請刪除'otherPropertyIsMissing'屬性。
  2. 在'otherPropertyIsMissing'屬性的onupgradeneeded方法中向對象庫中添加一個索引。例如,將其命名爲'indexOnOtherPropertyIsMissing'。
  3. 針對索引'indexOnOtherPropertyIsMissing'查詢所有對象。此查詢將只返回'indexOnOtherPropertyIsMissing'屬性不丟失的對象。這組對象是其他屬性丟失的所有對象。
+0

嗯,我想我可以給它一個初始值爲零而不是將它從表格中刪除。謝謝喬希。 –

相關問題