我一直试图使用db.put()更新单个字段,但无法使其正常工作。每次我用给定的ID更新单个字段时,它都会删除所有其他条目。下面是一个示例代码:
var schema = {
stores: [
{
name: 'items',
keyPath: 'id'
},
{
name: 'config',
keyPath: 'id'
}
]
};
var db = new ydn.db.Storage('initial', schema);
var items = [{
id: 1,
itemId: 'GTA5',
date:'03/25/2013',
description:'Great game'
}, {
id: 2,
itemId: 'Simcity',
date:'12/01/2012',
description:'Awesome gameplay'
}];
var config = {
id: 1,
currency: 'USD'
};
db.put('items', items);
db.put('config', config);
var updateTable = function(){
var req = $.when(db.count('items'),db.values('items'),db.get('config', 1));
var disp = function(s) {
var e = document.createElement('div');
e.textContent = s;
document.body.appendChild(e);
};
req.done(function(count,r,config) {
var currency = config.currency;
if(count > 0){
var n = r.length;
for (var i = 0; i < n; i++) {
var id = r[i].id;
var itemId = r[i].itemId;
var date = r[i].date;
var description = r[i].description
disp('ID: '+id+' itemID: '+itemId+' Currency: '+currency+' Date: '+date+' Description: '+description);
}
}
});
}
updateTable();
$('a').click(function(e){
e.preventDefault();
db.put('items',{id:2,description:'Borring'}).done(function(){
updateTable();
});
});下面是JSFiddle正在发生的事情的一个工作示例。如果单击"change“链接,则将更新指定的字段,但所有其他字段都是”未定义的“。
发布于 2013-10-03 15:02:55
是的,SimCity现在很无聊,但是明天又会带来兴奋。
IndexedDB本质上是一个密钥-文档存储。你必须作为一个整体来读或写一个记录。不可能只更新某些字段。事件如果您想要小的更新,您必须读取和写回整个记录。
读和写整个记录是可以的,但是对于一致性有一个重要的考虑。当您写回时,您必须确保您所拥有的记录没有被其他线程修改。即使javascript是单线程,因为读和写操作都是异步的,而且每个操作可能有不同的数据库状态。这似乎非常罕见,但经常发生。例如,当用户单击时,什么都不会发生,然后再次单击。从异步数据库的角度,这些用户交互被排队并并行执行。
一种常见的技术是在这两种操作中使用单个事务。在YDN-DB中,您可以通过三种方式进行操作。
使用显式事务:
db.run(function(tx_db) {
tx_db.get('items', 2).done(function(item) {
item.description = 'boring until Tomorrow';
tx_db.put(item).done(function(k) {
updateTable();
}
}
}, ['items'], 'readwrite');使用原子数据库操作:
var iter = ydn.db.ValueIterator.where('items', '=', 2);
db.open(function(cursor) {
var item = cursor.getValue();
item.description = 'boring until Tomorrow';
cursor.update(item);
}, iter, 'readwrite');编辑:
使用查询包装器:
db.from('items', '=', 2).patch({description: 'boring until Tomorrow'}); https://stackoverflow.com/questions/19158908
复制相似问题