How can I pass parameters to a view using cradle (CouchDB)

一曲冷凌霜 提交于 2019-12-12 15:43:34

问题


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)
{           
});

回答1:


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.




回答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) { ... });



来源:https://stackoverflow.com/questions/5573709/how-can-i-pass-parameters-to-a-view-using-cradle-couchdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!