Running Cloudant Queries through the Cloudant NPM Package

Cloudant is a recently-popular solution for cloud-based NoSQL databases. It is based heavily on CouchDB, and provides a very easy-to-use HTTP verb-based web service interface to carry out database operations.

When using Cloudant with Node.js or Express.js, the Cloudant NPM Package, which is basically a wrapper for the CouchDB NPM package known as nano, comes in handy. But while their documentation states how to execute various operations such as getting a document by its ID, doing bulk operations etc, it is quite obscure on how to execute the extremely useful operations based on Cloudant Query, which allows you to write complex selectors like the following:

 

{
  "selector": {
    "_id": "myid",
    "$or" : [
        {
          "$and" : [
            {
                "endDate" : {"$gt" : "2015-11-05"}
            },
            {
                "endDate" : {"$lte" : "2015-11-30"}
            }
          ]
        },
        {
          "$and" : [
              {
                  "startDate" : {"$gte" : "2015-11-05"}
              },
              {
                  "startDate" : {"$lt" : "2015-11-30"}
              }
          ]
        }
    ],
    "usertype":"admin"
  }
}

So how do you execute a query like that through the provided functions in the npm package for Cloudant? The secret lies in the find function provided in the package. The above could be executed as;

 


db.find({"selector": {
    "_id": "myid",
    "$or" : [
        {
          "$and" : [
            {
                "endDate" : {"$gt" : "2015-11-05"}
            },
            {
                "endDate" : {"$lte" : "2015-11-30"}
            }
          ]
        },
        {
          "$and" : [
              {
                  "startDate" : {"$gte" : "2015-11-05"}
              },
              {
                  "startDate" : {"$lt" : "2015-11-30"}
              }
          ]
        }
    ],
    "usertype":"admin"
  }
}, function(error, result) {});

And simple as that, you can execute any complex query that works on Cloudant Query using the Cloudant npm package.