3

Using cradle, how am I able to pass parameters to a view in CouchDB?


Update

Say I want to return documents which match other properties than _key (the default)...

// document format
{
    _key,
    postHeading,
    postBody,
    postDate
}

What if I wanted to match documents against the postHeading property... How would I go about this? What would the view look like, and how would I pass a search string to that view?


At the moment I'm doing this...

database.get("980f2ba66d5c8f9c91b9204a4d00022a", function (error, document)
{           
});

I would like to access a view instead, and instead of the 40 character long auto-generated key, I'd like to pass a string, matching another property.

Something along the lines of this...

database.save("_design/posts", {
    single: {
        map: function (document)
        {
            if (document.postHeading == PARAMETER_PASSED_GOES_HERE)
                emit(null, document);
        }
    }
});

database.view("posts/single", function (error, documents)
{           
});
cllpse
  • 21,396
  • 37
  • 131
  • 170

2 Answers2

3

If you are querying a view try to pass second parameter as options object with your settings, for example:

db.view('characters/all', {descending: true}, function (err, res) {
    res.forEach(function (row) {
        sys.puts(row.name + " is on the " +
                 row.force + " side of the force.");
    });
});

Also be aware of this:

Some query string parameters' values have to be JSON-encoded.


EDIT:

As far as I know you can't create a view in CouchDB where you pass your custom parameter which will be used in map/reduce function code. You have to emit keys from your map function and based on them you can query the view with parameters like startkey and endkey. Try to look at Database Queries the CouchDB Way article.

yojimbo87
  • 65,684
  • 25
  • 123
  • 131
  • But the descending parameter is a standard CouchDB parameter. I'd like to pass a custom parameter. I've updated my question. – cllpse Apr 07 '11 at 12:34
-2
db.get('vader', function (err, doc) {
    doc.name; // 'Darth Vader'
    assert.equal(doc.force, 'dark');
});

It looks like the searched value (parameter) here is 'dark' out of all force keys?

Cradle is also able to fetch multiple documents if you have a list of ids, just pass an array to get:

db.get(['luke', 'vader'], function (err, doc) { ... });

chris polzer
  • 3,219
  • 3
  • 28
  • 44