无法在Couchbase Lite - Android中获取自定义文档ID



我是Couchbase Android的新手。我使用Couchbase Lite v1.1.0将数据保存在本地。但是我面临着一些问题,什么时候这样做。我用谷歌搜索,在Couchbase Lite中阅读文档,并在stackoverflow中找到所有帖子,但我仍然不明白我所面临的是什么。

这是我的代码片段演示代码,用于将数据保存在数据库中,文档的自定义ID是索引i

cbManager=new Manager(new AndroidContext(context),
                    Manager.DEFAULT_OPTIONS);
cbDatabase=cbManager.getDatabase("my_db");
                 .....
for(int i=0; i<10; i++){
   Document document=cbDatabase.getDocument(String.valueOf(i)); // This line I custom document with id i
   Map<String,Object> docContent= new HashMap<String, Object>();
   docContent.put("title", title);
   docContent.put("firstName", firstName);
   docContent.put("lastName", lastName);
   try{
       document.putProperties(docContent);
   } catch (CouchbaseLiteException e){
       Log.e(TAG, "Cannot write document to database", e);
     }
}

并从Couchbase Lite获取所有数据:

 Query allDocumentsQuery= cbDatabase.createAllDocumentsQuery();
 QueryEnumerator queryResult=allDocumentsQuery.run();
 for (Iterator<QueryRow> it=queryResult;it.hasNext();){
      QueryRow row=it.next();
      
      Document doc=row.getDocument();
      String id=doc.getId(); // I get the id in here but the result is the default id (UUID):(
 }

所以,我有两个问题:

  1. 当我从数据库(couchbase lite)查询所有文档时,返回的文档默认ID(UUID),为什么它不返回我的自定义ID?

    表示:将所有文档保存到自定义 ID 的数据库中:1、2、3 ......9.但是从数据库获取时,所有文档的结果都有默认ID:UUID,UUID,...,UUID。)

  2. 我不明白为什么我按顺序保存文档,但所有文档的返回都不符合顺序?(因为这个原因使我自定义文档的ID)

请给我一些建议或指导我最好的方法。非常感谢大家。

您需要将

_rev 属性添加到映射中,并将 id 作为值。

以下是文档的摘录:

 putProperties(Map<String, Object> properties)
Creates and saves a new Revision with the specified properties. To succeed the specified properties must include a '_rev' property whose value maches the current Revision's id. 

所以你的代码应该看起来像这样:

Map<String,Object> docContent= new HashMap<String, Object>();
docContent.put("_rev", String.valueOf(i));
docContent.put("title", title);
docContent.put("firstName", firstName);
docContent.put("lastName", lastName);

最新更新