Tags

,

Sample script to delete/destroy a doc from a collection “mytable” based on the value of the column/field “fkId”.

Assume we have a collection "mytable" that looks like this
{
  "_id": "11111",
  "fkId": "12345",
  "name": "Tamiming"
},
{
  "_id": "22222",
  "fkId": "22333",
  "name": "Arf arf"
}
var Cloudant = require('cloudant');
var Config = require('config-js');
var config = new Config('./settings.js');
var username = config.get('CLOUDANT_USER');
var password = config.get('CLOUDANT_PASWORD');
var cloudant = Cloudant({account:username, password:password});
var mytableDb = cloudant.db.use('mytable');
var key = 'fkId';
var value = '12345';
...
...
mytableDb.list({
  'include_docs': true
}, function (err, body) {
  /* istanbul ignore next */
  if (err)
      res.json({success: false, msg: 'Unable to fetch documents'});
  else {
      var rows = body.rows;
      var items = [];
      var rec_found = false;
      rows.forEach(function (row) {
        if (row.doc[key] === value) {
          rec_found = true;
          items.push(row.doc);
        }
      });
      if (items.length === 0) {
        console.log("No record found with fkId: "+ value);
        res.json({success: true, msg: 'No record found with fkId: '+ value});
      } else {
        var docId = items[0]._id;
        var docRev = items[0]._rev;
        mytableDb.destroy(docId, docRev,  function(err) {
          if (!err) {
            console.log("Successfully deleted doc with fkId: "+ value);
            res.json({success: true, msg: 'Successfully deleted the item from the database.'});
          } else {
            res.json({success: false, msg: 'Failed to delete with fkId from the database, please try again.'});
          }
        });
      }
  }
});
Advertisements