The Cloudant connector enables LoopBack applications to connect to Cloudant data sources.Note: This page was generated from the loopback-connector-cloudant/README.md.

See also:

loopback-connector-cloudant

IBM Cloudant® is a NoSQL database platform built for the cloud. You canuse Cloudant as a fully-managed DBaaS running on public cloud platformslike Bluemix and SoftLayer or via an on-premises version called CloudantLocal.

For more information, see Getting started with Cloudant NoSQL DB

The loopback-connector-cloudant module is the Cloudant connector for the LoopBack framework.

Getting Started

Design

LoopBack tries best to fit its model to a specific database’s design, while limited by the nature of database, it’s not always possible to support all LoopBack features perfectly, and user should be aware of some key features about Cloudant before they start to design a Cloudant model.

Partial Update

Cloudant does not support the idea of updating a document. All “updates” on a document are _destructive replacements._

It implies that if you do want to partially update a document, please make sure unchanged values are included in the update object.

For example:

  1. // original document
  2. {
  3. "id": ...,
  4. "_rev": ...,
  5. "prop1": "1",
  6. "prop2": "2",
  7. }
  8. // data to be updated
  9. ds.updateOrCreate('User', {
  10. prop1: 'updated1',
  11. }, function (err, res) {});
  12. // document after update
  13. {
  14. "id": ...,
  15. "_rev": ...,
  16. "prop1": "updated1",
  17. }

Please note how property prop2 was completely dropped upon update.

We have some discussion on update methods, the issue link can be found in Feature Backlog section

Frequent Modification

Cloudant is not designed to change same document frequently and multiple times. It stores status changes by creating different documents and including the same unique id to tell that they are attached to the same item, not updating the same document.

By modeling the data in separate documents that are only written once, we can reduce the chance of concurrent access to the same document by separate processes.

And by properly controlling the conflict, developer can still do a safe modify. For details, refer to Conflict Control

Conflict Control

The basic idea is when modifying a document, user needs to control conflict by handling the revision of a document, currently the connector controls this process, after retriving the latest revision, connector uses it to update/delete doc, and returns 409 conflict error if doc changes during that time slot. In the middle, user could not interfere and provide their own conflict solution.

Model

Map Between Model And Document

Unlike relational db or mongodb, Cloudant doesn’t have a concept as ‘table’ or ‘collection’, data in a Cloudant database are all stored as documents.

The connector uses a design document to represent a LoopBack model, and common documents to represent model instances.

The following is a comparison among different databases:

ModelModel PropertyModel Instance
Relational DBtablecolumn in tablerow in table
MongodbcollectioncreateIndex if property.index is truedocument in collection
CloudantDesign documents in databaseNOT stored in documentcommon documents in database

To create a model, the connector creates a design document with the following config:

  1. type: 'text',
  2. name: 'lb-index-' + modelName,
  3. ddoc: 'lb-index-ddoc-' + modelName,
  4. index: {
  5. default_field: {
  6. enabled: false,
  7. },
  8. selector: {
  9. [modelIndex]: modelName
  10. },
  11. },

By default, modelIndex is ‘loopbackmodelname’, and modelSelector is {[modelIndex]: modelName}. User can customize modelSelector and modelIndex in datasource’s json file, for details please check model-specific configuration

To create a model instance, the connector creates a non-design document with value of property ‘loopbackmodelname’ equals to modelName.

For model properties, we plan to create index for property that has config index: true. In the future, it will be the same way as what mongodb connector does.

Model-specific Configuration

You can specify configurations per model for database selection and tomap a model to a different document:

common/models/_model-name.json_

  1. {
  2. "name": "User",
  3. "base": "PersistedModel",
  4. "idInjection": true,
  5. ...
  6. "cloudant": {
  7. "modelIndex": "custom_doc_type_property_name",
  8. "modelSelector": { "doc_type": "user" },
  9. "database": "test2"
  10. },
  11. ...

Model-specific configuration settings:

Property TypeDescription
databaseStringDatabase name
modelIndexStringSpecify the model name to document mapping, defaults to loopbackmodelname.
modelSelectorJSONUse the Cloudant Query selector syntax to associate models to existing data. NOTE: modelSelector and modelIndex are mutually exclusive; see Selector syntax.

_rev Property

In a document, property _rev is the latest doc revision and must be provided when modifying the doc.

Our connector allows the user to retrieve back the _rev property upon all CRUD operations, however does not add it to the model definition.

If you would like to have a _rev property on your model, as an end user, the onus is on you to add the property in the model definition.

Note: All CRUD operations require _rev (except create) and it is up to the user to specify them. The connector does not handle such cases due to possibilities of race condition when two users try to update the same document.

Example CRUD operations with _rev

model.json

  1. {
  2. ...
  3. "properties": {
  4. "_rev": {
  5. "type": "string"
  6. },
  7. "name": {
  8. "type": "string"
  9. }
  10. },
  11. ...
  12. }
  • Create
  1. Model.create([{
  2. name: 'Foo',
  3. }, {
  4. name: 'Bar',
  5. }], function(err, result) {
  6. if (err) throw err;
  7. console.log('Created instance: ' + JSON.stringify(result));
  8. });

Note: Cloudant does not allow customized _rev value, hence creating an instance with a _rev value will not give the expected result (i.e Cloudant’s CREATE operation ignores the _rev value when provided and generates a random unique one). The onus is on the user if they fail to comply to this rule.

Let’s say we have an instance in the database:

  1. {
  2. "id":"2",
  3. "_rev":"2-abcedf",
  4. "name":"Bar"
  5. }
  • Find

    • find
  1. Model.find(function(err, result) {
  2. if (err) throw err;
  3. console.log('Found all instances: ' + JSON.stringify(result));
  4. });
  • findById
  1. Model.findById('2', function(err, result) {
  2. if (err) throw err;
  3. console.log('Found instance with id: ' + JSON.stringify(result));
  4. });
  • Replace

    • replaceOrCreate
  1. Model.replaceOrCreate({
  2. id:'2',
  3. _rev:'2-abcedf',
  4. name:'Bar2'
  5. }, function(err, result) {
  6. if (err) throw err;
  7. console.log('Replace an existing instance: ' + JSON.stringify(result));
  8. });
  • replaceById
  1. Model.replaceById('2', {
  2. _rev:'2-abcedf',
  3. name:'Bar3'
  4. }, function(err, result) {
  5. if (err) throw err;
  6. console.log('Replace an existing instance with id: ' + JSON.stringify(result));
  7. });
  • Update

    • updateOrCreate
  1. Model.updateOrCreate({
  2. id:'2',
  3. _rev:'2-abcedf',
  4. name:'Bar4'
  5. }, function(err, result) {
  6. if (err) throw err;
  7. console.log('Update an existing instance: ' + JSON.stringify(result));
  8. });
  • update/updateAll

    • with _rev property
  1. Model.updateAll({
  2. _rev:'2-abcedf',
  3. name:'Bar4'
  4. }, {name: 'Bar4-updated', _rev: '2-abcedf'}, function(err, result) {
  5. if (err) throw err;
  6. console.log('Update an existing instance: ' + JSON.stringify(result));
  7. });
  1. - without <code>_rev</code> property
  1. Model.updateAll({
  2. name:'Bar4'
  3. }, {name: 'Bar4-updated'}, function(err, result) {
  4. if (err) throw err;
  5. console.log('Update an existing instance: ' + JSON.stringify(result));
  6. });

Force Id

In loopback forceId means user can specify the value of the primary key when creating a model instance, instead of using an auto-generated one. Learn more about LoopBack’s forceId.

We recommend user to be careful when creating customized model id instead of using the auto-generated one because data belonging to different models can interfere with each other.

Every document stored in Cloudant has an unique id, stored as _id, and the database has built-in index for it. Retrieving data by its _id gives a better performance than querying by other field. Therefore, the connector always assign the _id field as the loopback model’s primary key.

If you have two models that allow customized _id as primary key set with "forceId": false in the model definition, it could result in a document update conflict.

For example:

  1. {_id: 'myid', loopback__model__name: 'Foo'}
  2. {_id: 'myid', loopback__model__name: 'Bar'}

Here is an example of a case that would result in a document update conflict using "forceId": false:

model-definitions

  1. {
  2. "name": "Employee",
  3. "base": "PersistedModel",
  4. "idInjection": true,
  5. "forceId": false,
  6. "options": {
  7. "validateUpsert": true
  8. },
  9. "properties": {
  10. "_id": {
  11. "type": "number",
  12. "id": true,
  13. "required": true
  14. },
  15. "name": {
  16. "type": "string"
  17. },
  18. "age": {
  19. "type": "number"
  20. }
  21. },
  22. "validations": [],
  23. "relations": {},
  24. "acls": [],
  25. "methods": {}
  26. }
  1. {
  2. "name": "Car",
  3. "base": "PersistedModel",
  4. "idInjection": true,
  5. "forceId": false,
  6. "options": {
  7. "validateUpsert": true
  8. },
  9. "properties": {
  10. "_id": {
  11. "type": "number",
  12. "id": true,
  13. "required": true
  14. },
  15. "make": {
  16. "type": "string"
  17. },
  18. "model": {
  19. "type": "string"
  20. }
  21. },
  22. "validations": [],
  23. "relations": {},
  24. "acls": [],
  25. "methods": {}
  26. }

boot-script

  1. 'use strict';
  2. var util = require('util');
  3. var _ = require('lodash');
  4. module.exports = function(app) {
  5. var db = app.datasources.cloudantDs;
  6. var Employee = app.models.Employee;
  7. var Car = app.models.Car;
  8. db.once('connected', function() {
  9. db.automigrate(function(err) {
  10. if (err) throw err;
  11. console.log('\nAutomigrate completed');
  12. Employee.create([{
  13. _id: 1,
  14. name: 'Foo',
  15. }, {
  16. _id: 2,
  17. name: 'Bar',
  18. }], function(err, result) {
  19. if (err) throw err;
  20. console.log('\nCreated employee instance: ' + util.inspect(result));
  21. Car.create([{
  22. _id: 1,
  23. make: 'Toyota',
  24. }, {
  25. _id: 2,
  26. name: 'BMW',
  27. }], function(err, result) {
  28. if (err) throw err;
  29. console.log('\nCreated car instance: ' + util.inspect(result));
  30. });
  31. });
  32. });
  33. });
  34. };

Running the above script will throw a document update conflict because there exists a model instance with _id value of 1 and 2.

  1. Web server listening at: http://localhost:3000
  2. Browse your REST API at http://localhost:3000/explorer
  3. Automigrate completed
  4. Created employee instance: [ { _id: '1', name: 'Foo' }, { _id: '2', name: 'Bar' } ]
  5. /Users/ssh/workspace/sandbox/loopback-sandbox/apps/cloudant/cloudant-forceId-app/server/boot/script.js:33
  6. if (err) throw err;
  7. ^
  8. Error: Document update conflict. (duplicate?),Error: Document update conflict. (duplicate?)

In order to avoid this pitfall, please set "forceId": true on either of the model definition which would allow one of the models to have an auto-generated id or do not set "forceId": false on either of the model definitions.

Setup Cloudant Instance

For user that don’t have a cloudant server to develop or test, here are some suggestions can help you quickly setup one.

For development use, a docker container of Cloudant local is easy to setup and there is no request limit per second.

Bluemix Cloudant will be more stable for production.

  • Cloudant local (docker image)

  • Cloudant on Bluemix

    • Limit request per second by default.
    • Choose Bluemix Cloudant if you already have a Bluemix account with a better situation than limited-days’ free trial.

    • Setup steps:

      • Open Bluemix console: https://console.ng.bluemix.net
      • Login with your account.
      • Click on “CATALOG” in navigation bar.
      • Search with keyword “cloudant” and choose the “Cloudant NOSQLDB” under “Data and Analytics”.
      • Click on the green button “create” in the popup page to create your Cloudant database.
      • Go to “DASHBOARD” where you will see your new Cloudant DB icon under “Services”.
      • Click on the icon, and it will direct you to the database page. Check “Service Credentials” on the left to see your credentials.
      • Check “Manage” then click on button “LAUNCH” to see your Cloudant dashboard.
  • Cloudant DBaaS account

    • Limit request per second.
    • Limited free trial.
    • Sign up with https://cloudant.com/sign-up/ then you will see your Cloudant dashboard.To view the Cloudant dashboard on both DBaaS and Bluemix, sign in with your Cloudant username and password.

Installation

Enter the following in the top-level directory of your LoopBack application:

  1. $ npm install loopback-connector-cloudant --save

The —save option adds the dependency to the application’s package.json file.

Configuration

Generate Datasource

Use the Data source generator to add the Cloudant data source to yourapplication. The entry in the applications /server/datasources.json willlook something like this:

  1. "mydb": {
  2. "name": "mydb",
  3. "connector": "cloudant",
  4. "url": "https://<username>:<password>@<host>"
  5. "database": "test"
  6. }

or

  1. "mydb": {
  2. "name": "mydb",
  3. "connector": "cloudant",
  4. "username": "XXXX-bluemix",
  5. "password": "YYYYYYYYYYYY",
  6. "database": "test"
  7. }

Datasource Config

url vs username & password

  • NOTE: The url property will override username and password.

  • It means only when missing url, cloudant will use username and password to create connection.

  • If url is wrong, even user provide correct username and password, the connection still fails.

  • Only specify the username and password fields if you are using the root/admin user for the Cloudant server which has the samestring as the hostname for the Cloudant server, because the Cloudant driver used by the connector appends .cloudant.com to theusername field when username and password fields are specified. Therefore, it is good practice to use the url field insteadof username and password if your host is not username.cloudant.com.

  • Edit datasources.json to add other supported properties as required:

PropertyTypeDescription
databaseStringDatabase name
usernameStringCloudant username, use either ‘url’ or username/password
passwordStringCloudant password
urlStringCloudant URL containing both username and password
modelIndexStringSpecify the model name to document mapping, defaults to loopbackmodelname

Advanced configuration

Besides the basic configuration properties, user can provide advanced configuration information, for example proxy, in requestDefaults:

  1. "mydb": {
  2. "name": "mydb",
  3. "connector": "cloudant",
  4. "url": "https://<username>:<password>@<host>"
  5. "database": "test",
  6. "requestDefaults": {"proxy": "http://localhost:8080"}
  7. }

For details, refer to the driver(nodejs-cloudant) document

Requests Plugin

User can provide plugin name and parameters in datasource object. For example, connect to a Cloudant server with plugin called retry, with parameters retryAttempts and retryTimeout:

  1. "mydb": {
  2. "name": "mydb",
  3. "connector": "cloudant",
  4. "url": "https://<username>:<password>@<host>"
  5. "database": "test",
  6. "plugin": "retry",
  7. "retryAttempts": 5,
  8. "retryTimeout": 1000
  9. }

Please note user can only use one of the plugins list in Cloudant driver’s doc, not multiple:https://github.com/cloudant/nodejs-cloudant#request-plugins

Example Usage

/server/script.js

  1. var util = require('util');
  2. // Here we create datasource dynamically.
  3. // If you already define a static datasource in server/datasources.json,
  4. // please check how to load it in
  5. // https://github.com/cloudant/nodejs-cloudant#example-code
  6. var DataSource = require ('loopback-datasource-juggler').DataSource,
  7. Cloudant = require ('loopback-connector-cloudant');
  8. var config = {
  9. username: 'your_cloudant_username',
  10. password: 'your_cloudant_password',
  11. database: 'your_cloudant_database'
  12. };
  13. var db = new DataSource (Cloudant, config);
  14. Test = db.define ('Test', {
  15. name: { type: String },
  16. });
  17. // wait for connected event on the
  18. // datasource before doing any database
  19. // operations since we connect asynchronously
  20. db.once('connected', function() {
  21. Test.create({
  22. name: "Tony",
  23. }).then(function(test) {
  24. console.log('create instance ' + util.inspect(test, 4));
  25. return Test.find({ where: { name: "Tony" }});
  26. }).then(function(test) {
  27. console.log('find instance: ' + util.inspect(test, 4));
  28. return Test.destroyAll();
  29. }).then(function(test) {
  30. console.log('destroy instance!');
  31. }).catch(err);
  32. });

CRUD

User can find most CRUD operation apis documented in https://loopback.io/doc/en/lb3/Built-in-models-REST-API.html

We are still in progress of refactoring some methods, more details to be updated.

Update

Currently update does the same thing as replace, for details, refer to https://github.com/strongloop/loopback-connector-cloudant#no-partial-update

Migration

After attaching a model to a Cloudant datasource, either statically with model.json file or dynamically in boot script code, user need to run automigrate or autoupdate to migrate models to database. Cloudant connector does NOT automatically migrate them.

The following migration functions take either an array of multiple model’s name, or a string of a single model’s name. The example code will show how to do it.

autoupdate vs automigrate

autoupdate does not destroy existing model instances if model already defined in database. It only creates design document for new models. Under the hood Cloudant allows creating same design doc multiple times, it doesn’t return error, but returns existed as result to tell is it a new design doc or existing one.

automigrate destroys existing model instances if model already defined in database. Please make sure you do want to clean up data before running automigrate. Then it does same thing as autoupdate

isActual

User can call this function to check if model exists in database.

Example Code

/server/script.js

  1. module.export = function migrateData(app) {
  2. // Suppose you already define a datasource called `cloudantDS`
  3. // in server/datasources.json
  4. var ds = app.datasources.cloudantDS;
  5. // static model created with model.json file
  6. var StaticModel = app.models.StaticModel;
  7. // dynamic model created in boot script
  8. var DynamicModel = ds.define('DynamicModel', {
  9. name: {type: String},
  10. description: {type: String},
  11. });
  12. // Write the three examples in parallel just to avoid dup code,
  13. // please try ONLY ONE of them at one time.
  14. ds.once('connected', function() {
  15. // try autoupdate example - multiple models
  16. ds.autoupdate(['StaticModel', 'DynamicModel'], function(err) {});
  17. // OR
  18. // try automigrate example - single model
  19. ds.automigrate('StaticModel', function(err) {});
  20. // OR
  21. // try isActual example - if any model exist, run autoupdate, otherwise automigrate
  22. ds.isActual(['StaticModel', 'DynamicModel'], function(err, exist) {
  23. if (exist) {
  24. ds.autoupdate(['StaticModel', 'DynamicModel'], function(err){})
  25. } else {
  26. ds.automigate(['StaticModel', 'DynamicModel'], function(err){});
  27. }
  28. });
  29. });
  30. }

Discovery

Not implemented yet, track it in story https://github.com/strongloop/loopback-connector-cloudant/issues/118

Query

  • Uses Cloudant Query (Lucene) to support ad-hoc searching.
  • LoopBack query support for: fields, limit, order, skip and where filters.
  • Please check Advanced Queries for details about regex filter, nested filter and order.

View

Given a design doc name and the view name in it, user can use a connector level function viewDocs to query the view.

Since viewDocs is a specific api for Cloudant connector only, it is not attached to the dataSource Object defined in loopback-datasource-juggler, which means the correct way to call it is ds.connector.viewDocs:

/server/script.js

  1. module.exports = function(server) {
  2. // Get Cloudant dataSource as `ds`
  3. // 'cloudantDB' is the name of Cloudant datasource created in
  4. // 'server/datasources.json' file
  5. var ds = server.datasources.cloudantDB;
  6. ds.once('connected', function() {
  7. // 1. Please note `ds.connector.viewDocs()` is the correct way to call it,
  8. // NOT `ds.viewDocs()`
  9. // 2. This api matches the Cloudant endpoint:
  10. // GET /db/_design/<design-doc>/_view/<view-name>
  11. ds.connector.viewDocs('design_doc', 'view_name', function(err, results) {
  12. // `results` would be the data returned by querying that view
  13. });
  14. // Alternatively user can also specify the filter for view query
  15. ds.connector.viewDocs('design_doc', 'view_name', {key: 'filter'},
  16. function(err, results) {});
  17. });
  18. };

Geospatial

Given a design doc name and the filter name in it, user can use a connector level function geoDocs to query a geospatial index.

Since geoDocs is a specific api for Cloudant connector only, it is not attached to the dataSource Object defined in loopback-datasource-juggler, which means the correct way to call it is ds.connector.geoDocs:

/server/script.js

  1. module.exports = function(server) {
  2. // Get Cloudant dataSource as `ds`
  3. // 'cloudantDB' is the name of Cloudant datasource created in
  4. // 'server/datasources.json' file
  5. var ds = server.datasources.cloudantDB;
  6. ds.once('connected', function() {
  7. // 1. Please note `ds.connector.geoDocs()` is the correct way to call it,
  8. // NOT `ds.geoDocs()`
  9. // 2. This api matches the Cloudant endpoint:
  10. // GET /db/_design/<design-doc>/_geo/<index-name>
  11. ds.connector.geoDocs('design_doc', 'index_name', function(err, results) {
  12. // `results` would be the data returned by querying that geospatial index
  13. });
  14. // Alternatively user can also specify the filter for geospatial query
  15. ds.connector.geoDocs('design_doc', 'index_name', {key: 'filter'},
  16. function(err, results) {});
  17. });
  18. };

Bulk replace

Given an array of data to be updated, Cloudant supports the idea of performing bulk replace on a model instance. Please note, unlike other CRUD operations, bulk replace does not invoke any operation hooks.

Note: To perform bulk replace, each data in the array data set needs to have the id and _rev property corresponding to the documents id and _rev property in the database.

Example:

  1. ```javascript
  2. var dataToCreate = [
  3. {id: 1, name: 'Foo', age: 1},
  4. {id: 2, name: 'Bar', age: 1},
  5. {id: 3, name: 'Baz', age: 2},
  6. {id: 4, name: 'A', age: 4},
  7. {id: 5, name: 'B', age: 5},
  8. {id: 6, name: 'C', age: 6},
  9. {id: 7, name: 'D', age: 7},
  10. {id: 8, name: 'E', age: 8},
  11. ];
  12. var dataToUpdate = [
  13. {id: 1, name: 'Foo-change', age: 11},
  14. {id: 5, name: 'B-change', age: 51},
  15. {id: 8, name: 'E-change', age: 91}
  16. ];
  17. module.exports = function(app) {
  18. var db = app.dataSources.cloudantDS;
  19. var Employee = app.models.Employee;
  20. db.once('connected', function() {
  21. db.automigrate(function(err) {
  22. if (err) throw err;
  23. Employee.create(dataToCreate, function(err, result) {
  24. if (err) throw err;
  25. console.log('\nCreated instance: ' + JSON.stringify(result));
  26. dataToUpdate[0].id = result[0].id;
  27. dataToUpdate[0]._rev = result[0]._rev;
  28. dataToUpdate[1].id = result[4].id;
  29. dataToUpdate[1]._rev = result[4]._rev;
  30. dataToUpdate[2].id = result[7].id;
  31. dataToUpdate[2]._rev = result[7]._rev;
  32. // note: it is called `db.connector.bulkReplace`
  33. // rather than `Employee.bulkReplace`
  34. db.connector.bulkReplace('Employee', dataToUpdate, function(err, result) {
  35. if (err) throw err;
  36. console.log('\nBulk replace performed: ' + JSON.stringify(result));
  37. Employee.find(function(err, result) {
  38. if (err) throw err;
  39. console.log('\nFound all instances: ' + JSON.stringify(result));
  40. });
  41. });
  42. });
  43. });
  44. });
  45. };

Testing

  • Cloudant local(docker image)

  • Cloudant DBaaS account

    • username: your sign up username
    • password: your sign up password
    • database: create your own database for testing
  • Cloudant on Bluemix

    • username: see services credentials
    • password: see services credentials
    • database: create your own database for testingTo run the tests:
  1. CLOUDANT_URL=url CLOUDANT_DATABASE=database npm test

OR

  1. CLOUDANT_USERNAME=username CLOUDANT_PASSWORD=password CLOUDANT_DATABASE=database npm test

Currently the imported test cases from juggler doesn’t fit Cloudant connector, to skip them, set CI=1 in command when run tests.

Docker

  • Assuming you have Docker installed, run the following script which would spawn a Cloudant instance on your local:
  1. source setup.sh <HOST> <USER> <PASSWORD> <PORT> <DATABASE>

where <HOST>, <PORT>, <USER>, <PASSWORD> and <DATABASE> are optional parameters. The default values are localhost, 8080 admin, pass and testdb respectively.

  • Run the test:
  1. npm run mocha

More Info

For more detailed information regarding connector-specific functions and behaviour,see the docs section.

Feature backlog

Index

To be updated

Tags: connectorsreadme