Emulating dynamic parameters with views
Consider the following document structure...
{
_id,
_rev,
postTitle,
postBody
}
I'm writing a small nodeJS weblog application, where I'd like my URLs to reflect a posts title. For instance /WebLog/Posts/View/Hello-World/
.
Since it's not possible to query CouchDB on anything but the _id property, does it make sense that I create a view for each post, in order to map a postTitle
to an _id
?
开发者_开发百科How would you go about querying other document-properties than the _id
?
... Should I just forfeit and use MongoDB or MySQL instead? Am I asking too much of CouchDB?
Views are how you create indexes in CouchDB. To get documents by postTitle
, use a view, the keys of which are postTitle
s, and query it with key=<title>
and includedocs=true
.
{
"views": {
"by-post-title": {
"map": "function(doc) { emit(doc.postTitle, null); }"
}
}
}
And the query: GET /<db>/_design/<design>/_view/by-post-title?includedocs=true&key="Hello-World"
Learn more about CouchDB views on the CouchDB Wiki.
You've partially answered your own question, but yes you'll create a view, as mentioned by an answerer earlier.
"views": {
"by-post-title": {
"map": "function(doc) {
if(doc.postTitle){
var titleURL = postTitle.split(" ").join("_");
emit(doc.titleURL, {"body" : doc.postBody, "title": doc.postTitle);
}
}"
}
}
now, http://yourcouchdb:yourport/yourdb/_design/by-post-title/_view/by-post-title?key="Hello_World" would return your postBody and postTitle.
Since your documents can contain other key:values, it is best not to return entire doc as the second parameter in emit calls.
Please don't do a view for each post, that sounds painful to maintain. However, you could use either Django (with Couchdb) or Couchapp, and both have good url rewriting abilities. Also, look at this on the couchone website:
couchdb rewrites in 0.11
精彩评论