Bucket.get() throws null pointer exception

query

#1

Hi. I am searching for a document in Couchbase using the document’s id. I am able to retrieve it when the document actually exists. If I give an ID which is not in the database, .get function returns NullPointerException, but I want a new document to be created with that ID when that happens. Is this possible?


#2

Hi,
Get returns null when the id cannot be found (you are probably calling
content() without checking for a null I guess). So you could check if null
and in that case revert to an insert. Note that if in the meantime the
document has been concurrently created, insert will fail with a
DocumentAlreadyExistException.


#3

Hi,

This is my code to find a document.

public Customer findCustomerDocId(String docId) throws NullPointerException{
    Gson gson = new GsonBuilder().create();
    JsonDocument fDoc = theBucket.get(docId);
    Customer cust = gson.fromJson(fDoc.content().toString(), Customer.class);
    return cust;
}

I understand that when the document is not found, NullPointerException is thrown. Now when this happens, I immediately want to create a new document with the specified docId. I don’t have control over the .get() function right? How can I handle this? I also have a feeling that you understood what I actually want, but I didn’t completely understand you answer.


#4

the NullPointerException happens because when you build your Customer you call fDoc.content() but fDoc is null.
What you can do is:

public Customer findCustomerDocId(String docId) throws NullPointerException{
    Gson gson = new GsonBuilder().create();
    JsonDocument fDoc = theBucket.get(docId);
    if (fDoc == null) {
        //create the content. JSON String?
        String newContent;
       //create the doc and store
       RawJsonDocument newDoc = RawJsonDocument.create(docId, newContent);
       theBucket.insert(newDoc);
       //you should have also a Customer object at this point, to return
       return ???;
    } else {
        Customer cust = gson.fromJson(fDoc.content().toString(), Customer.class);
        return cust;
    }
}