javascriptnode.jscouchdbcouchdb-futoncradle

How do I add a new key-value pair to CouchDB using Cradle? Node.js


I have a document in my CouchDB database I would like to add a new key-value pair to. I am using Cradle to communicate with the DB (https://github.com/cloudhead/cradle), however, I get an error if I try to update it with a field that doesn't exist. My document is layed out like this:

{
 "_id": "document",
 "_rev": "some_revision",
 "key1": "index.html",
 "key2": "hows.html",
 "key3": "about.html"
}

And the code I was trying to use looks like this:

db.merge('document', {
        req.body.key: req.body.value
      }, function (err, res) {
        console.log('added to document')
    });

And the error I get looks like this:

SyntaxError: Unexpected token .

Referring to the (.) in between the req.body.

Does anyone have any good direction on how to handle to this? Cradle has been great to me so far, but this seems more difficult than it should be!


Solution

  • That's just a Javascript issue - nothing due to Cradle. You can't do this to set a dynamically named prop:

      {
        req.body.key: req.body.value
      }
    

    You'll need to do this like so:

    var temp = {}
    temp[req.body.key] = req.body.value
    db.merge('document', temp, ...