couchdb query a view with key parameters

↘锁芯ラ 提交于 2020-01-02 01:37:51

问题


Without a key parameter, the view works correctly

$curl "http://127.0.0.1:5984/music/_design/albums/_view/by_release_date"

{"total_rows":311,"offset":0,"rows":[
{"id":"a4327d0718d3b1e227df7124a99a7fc3","key":"1991-12-22","value":{"by":"张楚","title":"黑月亮"}},
{"id":"a4327d0718d3b1e227df7124a99a3ac5","key":"unknown","value":{"by":"郑钧","title":"郑钧:赤裸裸"}},

but when with a key, i got either bad request response or empty result. Why?

$curl "http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?key=unknown" {"error":"bad_request","reason":"invalid_json"}

$curl "http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?key=1993" {"total_rows":311,"offset":0,"rows":[

]}

The map function is:

map
function(doc) {
  key = doc.release_date
  value = {by: doc.author , title: doc.title}
  emit(key, value);
}

回答1:


The key is a string hence you need to include " = %22, e.g http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?key=%221993%22




回答2:


I guess you are trying to query key range. Try to specify startkey and endkey:

http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?startkey=1993&endkey=1993z

More details: http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options




回答3:


Here is how i deal with it

let serverURL = "SERVER_IP:5984"
let dd_name = 'email' // for example
let viewname = "by_email" // for example

const findDocByEmail = email => {
  let url = `${serverURL}/_design/${dd_name}/_view/${viewname}?key="${email}"`
  fetch(url, {
    method: 'GET',
    mode: "no-cors",
    headers:{
      'Content-Type': 'application/json',
      'Authorization': 'Basic ' + btoa('COUCH_USER:SECRET'), // you can remove this if not needed,
    }
  })
  .then(res => {
    return res.json()
  })
  .then(response => console.log('Response: ', response))
  .catch(error =>  console.log(error))

}


来源:https://stackoverflow.com/questions/19887268/couchdb-query-a-view-with-key-parameters

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