Cloudant Fundamentals: Programmatic CRUD
In this post we’ll look at equivalent tasks using programmatic means.
You don’t need a special library to work with Cloudant — just something capable of making HTTP requests. The libraries do help, however, with authentication and parameter encoding. There are three officially supported libraries for three programming languages:
For these examples I’m going to use the cloudant-quickstart library that makes it easy for you to get started with Cloudant. It is installed by simply typing
npm install cloudant-quickstart into your terminal.
You can copy the following code snippets into either:
- a Node “REPL” (just type
nodeon the command line)
- a Jupyter notebook using the pixiedust_node library
- a text file
Connect to the database
First we need a URL containing our Cloudant credentials and to start up the library:
Create the database
Creating a database is as simple as calling the
Let’s say we want to add an array of documents to our database:
insert document can be used to write them to the database:
The same goes for single documents:
Documents can be read back singly by specifying the ID of the document you want:
You may also specify a list of ids:
Or ask for all the documents:
The cloudant-quickstart library allows documents to be updated without worrying about revision tokens: just pass in the new document body and the library will figure it out:
The library will even allow you to make incremental updates to documents by passing the document id, an object containing the changes, and
true (to indicate that the updates are to be merged in) as three parameters to the
Deleting a document
A documents can be removed from the database by passing an ID
Where did the rev token go?
The cloudant-quickstart library hides the rev token from you. The rev token is a tricky concept for new starters, so this library abstracts it from you so that you can get on with building something quickly. In a production environment, you will have to get to grips with revision tokens, but for now we can sit back and relax.
In the next post we’ll look at querying data. Until then!