CouchBase Lite - 更新文档 - Android,为什么需要“properties.putAll(..)”?

问题描述 投票:3回答:1

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();
        }
    }
android couchbase couchbase-lite
1个回答
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");
}
© www.soinside.com 2019 - 2024. All rights reserved.