Finding Documents Array CouchDB

2019-09-04 05:38发布

问题:

I have Documents they have this structure:

{id: ####,
rev: ####,
"Cam_name": "Camera SX",
"colour": "white",
"manufacturer": "Sony",
"rec_limit": 180,
"Customer": ["Mike","Ann","James"]
}

{id: ####,
rev: ####,
"Cam_name": "PXSV CAM",
"colour": "white",
"manufacturer": "LG",
"rec_limit": 144,
"Customer": ["Mike","Oliver","Mr. Rain"]
}

{id: ####,
rev: ####,
"Cam_name": "LxSV Double",
"colour": "white",
"manufacturer": "Phillips",
"rec_limit": 160,
"Customer": ["Mike"]
}

And i want to make an MAP Function query where i can see ALL Cam_Names which the Customer Mike is using.

i have a simillar Map Function but this shows only the Cam_Name LxSV Double and only the Customer Mike. i want to show all Cam_Names which mike is using.

MyQuery:

function(doc){
if(doc.Customer == "Mike"){
emit(doc.Cam_name, doc.Customer)

This query gives me not the right result.

回答1:

If your query looks exactly like that, then you have a syntax error. But also, doc.Customer is an array, so you can't do a simple equality check.

But checking the existence of a value in an array is totally unnecessary, your map function can simply look like this:

function (doc) {
  doc.Customer.forEach(function (customer) {
    emit(customer, doc.Cam_name);
  });
}

Then, query your view with /{db}/_design/{ddoc}/_view/{view}?key="Mike"

Your output will look like:

{
  "total_rows": 3,
  "offset": 0,
  "rows": [
    {
      "id": "####",
      "key": "Mike",
      "value": "Camera SX"
    },
    {
      "id": "####",
      "key": "Mike",
      "value": "PXSV CAM"
    },
    {
      "id": "####",
      "key": "Mike",
      "value": "LxSV Double"
    }
  ]
}

Now, you can use this same view to find any customer, not just whomever you specify in your map function.