javascriptnode.jscouchdbcradle

Using variables in Cradle Merge (Node.js and CouchDB)


I'm trying to write a function that loops and changes a field in multiple documents at the same time. The only issue is that when I'm passing a parameter value, the cradle merge seems to actually pass a field with the parameter name instead of the value.

For example:

function saveToAll(field, data) {
  db.get('document_list', function (err, doc) {
      for (key in doc.doc_list_pure) {
        //Create a Closure
        (function(key1) {
          console.log(key1)
            //Go into the DB
            console.log(field);
            console.log(data);
             db.merge(key1, {
              field : data
            }, function (err, res) {
                console.log('Saved');
            });
         }
        )(key)
      }
});
}

So here, if I write a function like this:

saveToAll("new_field", value);

It will log correctly, but save a field literally called 'field' with the correct data. Does anyone have an idea of how to approach this? Is this a cradle bug or just me?


Solution

  • Try this:

    function saveToAll(field, data) {
      db.get('document_list', function (err, doc) {
          for (key in doc.doc_list_pure) {
            //Create a Closure
            (function(key1) {
              console.log(key1)
                //Go into the DB
                console.log(field);
                console.log(data);
                var dataObj = {};
                dataObj[field]=data;
    
                db.merge(key1, dataObj, function (err, res) {
                    console.log('Saved');
                });
             }
            )(key)
          }
    });
    }