Here介绍了如何在Couchbase Lite中更新文档。
我注意到如果我在下面的代码中取消注释properties.putAll(doc.getProperties());
,那么更新就不会发生,为什么?
Document doc = database.getDocument(myDocID);
Map<String, Object> properties = new HashMap<String, Object>();
properties.putAll(doc.getProperties()); // IF I UNCOMMENT THIS LINE, THE UPDATE DOES NOT WORK, WHY ?
properties.put("title", title);
properties.put("notes", notes);
try {
doc.putProperties(properties);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
我的猜测是,这是因为一些隐藏的属性,但不确定。
编辑:
以下是显示此问题的另一个示例代码:
static public void storeDoc(Database db, String key, Map<String, Object> p){
// Save the document to the database
Document document = db.getDocument(key);
Map<String, Object> p1 = new HashMap<>();
Map<String, Object> oldprops=document.getProperties();
if (oldprops!=null) p1.putAll(oldprops); //if I uncomment this line then the update does not work
for (Map.Entry<String, Object > e:p.entrySet()) {
p1.put(e.getKey(),e.getValue());
}
try {
document.putProperties(p1);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
检索文档时,您将获得一个包含不可变数据版本的副本。您可以通过将地图复制到单独的地图对象,然后覆盖旧地图来处理此问题。
如果您不想另外使用putAll,可以使用createRevision()获取新的UnsavedRevision。这将返回最新版本的副本,但内容可变。然后,您可以直接操作属性映射。通过调用save()来提交更改。
UnsavedRevision update = document.createRevision();
profile = update.getProperties();
profile.put("type", "profile"); // Add a "type" to the document
try {
update.save();
} catch (CouchbaseLiteException ex) {
Log.e(TAG, "CBL operation failed");
}