couchdb使用关键参数查询视图

时间:2013-11-10 07:21:17

标签: json couchdb

没有关键参数,视图可以正常工作

$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":"郑钧:赤裸裸"}},

但是当使用密钥时,我得到了错误的请求响应或空的结果。为什么呢?

$curl "http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?key=unknown" { “错误”: “BAD_REQUEST”, “理由”: “invalid_json”}

$curl "http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?key=1993" { “TOTAL_ROWS”:311, “偏移”:0, “行”:[

]}

地图功能是:

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

3 个答案:

答案 0 :(得分:34)

密钥是一个字符串,因此您需要包含" = %22,例如http://127.0.0.1:5984/music/_design/albums/_view/by_release_date?key=%221993%22

答案 1 :(得分:1)

我猜您正在尝试查询关键范围。尝试指定startkeyendkey

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

更多详情:http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options

答案 2 :(得分:0)

这是我的处理方式

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))

}