Creating documents

A document may be created using the lcb_store() function. The lcb_store() function accepts an array lcb_store_cmd_t structure pointers containing the specifics of the item to store and various modifiers controlling its value and metadata:

static void on_stored_status(lcb_t instance, const void *cookie, lcb_storage_t op, lcb_error_t err, const lcb_store_resp_t *resp)
{
  if (err != LCB_SUCCESS) {
    fprintf(“Couldn’t store item to cluster: %s\n”, lcb_strerror(instance, err));
  }
}

// Error checking for initialization left out for brevity
static void storeDoc() {
  // ...
  lcb_set_store_callback(instance, on_stored_status);
  struct lcb_store_cmd_st cmd = { 0 };
  const struct lcb_store_cmd_t *cmdlist = &cmd;
  
  const char *doc = "{ \"json\" : \"data\" }";
  const char *key = "a_simple_key";
  cmd.v.v0.key = key;
  cmd.v.v0.nkey = strlen(key);
  cmd.v.v0.bytes = doc;
  cmd.v.v0.nbytes = strlen(doc);
  cmd.v.v0.operation = LCB_ADD;
  
  lcb_error_t err = lcb_store(instance, NULL, 1, &cmdlist);
  if (err == LCB_SUCCESS) {
    lcb_wait(instance);
  } else {
    fprintf(stderr, “Couldn’t schedule operation: %s\n”, lcb_strerror(instance, err));
  }
}

Before talking about the on_stored_status function, let’s talk about the init_and_store() functions. The first few lines create and initialize a new libcouchbase instance as shown above. After that’s done we initialize an lcb_store_cmd_t structure that contains information about what we want to store.

The key and nkey fields contain buffer and length of the key itself, while the bytes and nbytes fields contain the buffer and the length of the document. The operation field describes how to store the document. In this case LCB_ADD means to only create the document if it does not already exist.

If the operation was successully scheduled, the lcb_store() function will return LCB_SUCCESS, in this case you can call lcb_wait() for the operation to be performed on the cluster. While lcb_wait() is being called, the callback (in this case, on_stored_status() will be invoked with information about the document just stored. This also carries an error code if the document could not be stored to the cluster. A common error code for the LCB_ADD operation is LCB_KEY_EEXISTS, which means the cluster did not store the document because it already exists.