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();
}
}
最佳答案
当您检索文档时,您会得到一份副本,其中包含数据的不可变版本。您可以通过将 map 复制到单独的 map 对象,然后覆盖旧 map 来解决这个问题。
如果您不想使用 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");
}
关于android - CouchBase Lite - 更新文档 - Android,为什么需要 "properties.putAll(..)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669484/