On Wed, Apr 11, 2012 at 9:24 PM, Julien Dreux wrote:
> function(doc) {
> if(doc.businessHours) {
> var daysArr = new Array('s','m','t','w','h','f','a');
> var day = daysArr[new Date().getDay()];
> emit(parseInt(doc.businessHours[day][0].indexOf('0') == 0 ?
> doc.businessHours[day][0].substring(1) : doc.businessHours[day][0]), doc)};
> }
>
> Thank you for your help.
> *
> *
> *JULIEN DREUX*
> jdreux@justlexit.com
> 514 812-8084
> www.justlexit.com
>
As said before, views (both map and reduce) MUST be absolutely
context-independent. There is only ONE thing a map function can depend
on : the document being processed. It cannot even rely on other
documents, or the version of your couchdb, or whatever. If you need
this information, include it in your doc.
I get from your view definition that you would like to ask your
database for the opening hours of your businesses for today, right ? I
will suppose you do so. A correct way to implement way would be like
that :
- for each day in the 'businessHours' array of the doc, emit a pair.
The key should be the day from the array, the value would be the
opening hour as processed in your emit (removing the leading 0 if it
exists)
- You would then have multiple key/value pairs by document.
- At query time, use 'key=' as an
argument, like 'key="s"'.
- Bonus : do not emit the doc in a map. If you need it, you can add
'include_docs=true' to the arguments at querying time, and you will be
able to access it along the data you emitted when defining the view.
This will prevent you from storing the doc twice.
Proposed (untested) implementation :
function(doc){
var daysArr = new Array('s','m','t','w','h','f','a');
var i=0;
for (i = 0; i < daysArr.length; i++){
var day = daysArr[i];
var openingHour = doc.businessHours[day][0].indexOf('0') == 0 ?
doc.businessHours[day][0].substring(1) : doc.businessHours[day][0]);
emit(day, openingHour);
}
}
Query would look like this for today (wednesday) :
GET /path/to/view?key="w"&include_docs=true
--
Matthieu RAKOTOJAONA