【发布时间】:2017-04-07 09:00:46
【问题描述】:
我正在尝试使用一些 JavaScript 创建一个非常简单的 IndexedDB,但它已经在 on 处理程序中失败了。显然浏览器(Chrome 57)无法parsekeyPath(在Basic Concepts)我的存储空间。
我或多或少都在关注这些简单的例子:MDN 或 Opera-Dev。
假设我想在数据库中存储像这样的对象:
{
"1": 23, // the unique id
"2": 'Name',
"3": 'Description',
"4": null,
"5": null
}
代码如下:
var sStoreNodes = 'nodes';
var sIdFieldNode = '1'; // the important part
// event is fired for creating the DB and upgrading the version
request.onupgradeneeded = function(event)
{
var db = event.target.result;
// Create an objectStore for nodes. Unique key should be the id of the node, on property 1.
// So ID will be the key!
var objectStore = db.createObjectStore(
sStoreNodes,
{
// changing to a plain string works, if it is a valid identifier and not just a strigified number
'keyPath' : [ sIdFieldNode ],
'autoIncrement' : false // really important here
});
};
错误信息如下:
未捕获的 DOMException:无法在“IDBDatabase”上执行“createObjectStore”:keyPath 选项不是有效的密钥路径。 在 IDBOpenDBRequest.CCapIndexedDB.request.onupgradeneeded
我也可以尝试省略关键路径,但我想知道为什么会发生这种情况,如果我真的需要使用(复杂的)关键路径,我可以做些什么。
关于规格:
我不确定,this是否可以在这里应用:
如果一个值是以下 ECMAScript [ECMA-262] 类型之一,则称其为有效键:数字原始值、字符串原始值、日期对象或数组对象。
以及this 的实际含义:
如果键路径是 DOMString,则 [用于获取键路径] 的值将是等于键路径的 DOMString。如果键路径是序列,则值将是一个新数组,通过附加与序列中每个 DOMString 相等的字符串来填充。
编辑 如果您不使用字符串化数字,而是使用字符串,这是有效的标识符(以字符 [a-zA-Z] 开头),则此方法有效。所以'keyPath' : 'b' 没问题。我猜这是因为这个值用于创建像a.b.c 这样的路径。
【问题讨论】:
标签: javascript indexeddb key-value-store