使用keyPath在IDBObjectSore中创建indexedDB索引的方法如下:'location:location._id'



我在索引数据库存储中有一些数据,如下所示:

{
"assetNo" : "00045455",
"location:location" : {
"title" : "19100003BRMA2879",
"_id" : "5e2727cbc38a923f5826efb7"
}
}

我想在该位置内的_id上创建一个索引,但似乎 indexedDB 不喜欢 location:location 之间的冒号。 我收到错误:DOMException:无法在"IDBObjectStore"上执行"createIndex":keyPath 参数包含无效的键路径

冒号是通过成千上万的代码行使用的约定,因此仅更改它就会成为问题。 有没有办法解决这个问题? 例如,一种逃避结肠的方法?

查看 https://www.w3.org/TR/IndexedDB-2/#key-path-construct 我看到它指出:

有效的密钥路径是以下路径之一:

  • 一个空字符串。
  • 标识符,它是与 ECMAScript 语言规范 [ECMA-262] 中的 IdentifierName 生产匹配的字符串。
  • 由两个或多个标识符组成的字符串,由句点分隔(U+002E 句号(。
  • 仅包含符合上述要求的字符串的非空列表。

密钥路径中不允许有空格。

冒号似乎违反了第二个要点。

是否可以在写入和读取数据库时更改数据?这是存储数据时很常见的事情,有时您需要修改实际保留的内容。

像这样:

function write(db, object) {
return new Promise((resolve, reject) => {
const transaction = db.transaction('mystore', 'readwrite');
transaction.oncomplete = resolve;
transaction.onerror = event => reject(event.target.error);
const store = transaction.objectStore('mystore');
// what i am suggesting, modify just before write
// the extra cloning is to avoid side effects on input
const clone = { ...object };
clone.location_location = clone['location:location'];
delete clone['location:location'];
store.put(clone);    
});
}
function onupgradeneeded(event) {
const db = event.target.result;
const store = db.createObjectStore('mystore');
db.createIndex('location_id', 'location_location._id');
}
function getByLocationId(db, id) {
return new Promise((resolve, reject) => {
const transaction = db.transaction('mystore');
const store = transaction.objectStore('mystore');
const index = store.index('location_id');
const request = index.get(id);
request.onerror = event => reject(request.error);
request.onsuccess = event => {
const result = event.target.result;
// if we found something, project output as if we stored 
// it with a colon. we do not need to clone here.
if (result) {
result['location:location'] = result.location_location;
delete result.location_location;
}
resolve(result);
};
});
}

最新更新