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

时间:2016-01-21 18:00:40

标签: java android couchbase couchbase-lite

我是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)
  3. 请给我一些建议或指导我做最好的方法。非常感谢你们。

1 个答案:

答案 0 :(得分:0)

您需要将_rev属性添加到地图中,并将ID作为值。

以下摘自documentation

 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);
相关问题