tej shah
tej shah

Reputation: 3095

facing error when insert custom _id in cloudant document?

When I don't set the _id I can insert a document, however, when I add _id then I receive an error:

Failed to create document java.util.concurrent.ExecutionException:
   com.cloudant.sync.datastore.InvalidDocumentException: Field name start
   with '_' is not allowed.

My code is:

private Map<String, String> temponload() {
    Map<String, String> userInfo = new HashMap<>();
    userInfo.put("_id", "org:HELLO"+str_email);
    userInfo.put("first_name", "FIRSTNAME");
    userInfo.put("last_name", "LASTNAME");

    return userInfo;
}
public Map<String, String> createDocument(Map<String, String> map) {
    DocumentRevision rev = new DocumentRevision();
    rev.setBody(DocumentBodyFactory.create(map));
    try {
        DocumentRevision created = sunDatastore.createDocumentFromRevision(rev);
        return map;
    } catch (DocumentException de) {
        return null;
    }
}

Please help me for this issue

Upvotes: 0

Views: 96

Answers (2)

rhyshort
rhyshort

Reputation: 1453

_ prefixed fields in CouchDB/Cloudant are meta-data fields.

In the library you are using (sync-android on github), meta-data fields are accessed via getters on the DocumentRevision object itself and the document body is rejected if if it has _ prefixed fields.

The meta-data fields are:

  • _id
  • _rev
  • _deleted

To set the ID for the document you must use the constructor as per Chris Snow's answer. If the ID is not set for a document the library will generate an ID for that document, which is why it successfully saves if you omit the _id from the body of the document.

Upvotes: 1

Chris Snow
Chris Snow

Reputation: 24606

Can you use the constructor where you pass in the Id to DocumentRevision, i.e.

DocumentRevision(java.lang.String id) 

Source: http://www.javadoc.io/doc/com.cloudant/cloudant-sync-datastore-javase/1.1.5

Upvotes: 0

Related Questions