如何获得没有特定字段的对象?

时间:2017-01-09 19:22:12

标签: indexeddb

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

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

1 个答案:

答案 0 :(得分:2)

你不能以直截了当的方式做到这一点。无法查询丢失/空字段。

但是,你可以聪明并解决这个问题。

  1. 在对象存储中存储对象之前,请检查对象的属性是否为空(null / undefined / empty string / etc)。如果字段丢失,请设置一个单独的字段,例如&#39; otherPropertyIsMissing&#39;一个价值。我建议使用空字符串(&#39;&#39;)或0.如果该属性没有丢失,请删除&#39; otherPropertyIsMissing&#39;属性。
  2. 在onupgradeneeded方法的&#39; otherPropertyIsMissing&#39;上添加索引到对象库。属性。例如,将其命名为indexOnOtherPropertyIsMissing&#39;。
  3. 查询索引&#39; indexOnOtherPropertyIsMissing&#39;对于所有对象。此查询仅返回&quot; indexOnOtherPropertyIsMissing&#39;财产不缺。这组对象是缺少其他属性的所有对象。