Reputation: 4098
I have a simple document named Order structure with the fields id, name, userId and timeScheduled.
What I would like to do is create a view where I can find the document.id for those who's userId is some value and timeScheduledis after a given date.
My view:
"by_users_after_time": {
"map": "function(doc) { if (doc.userId && doc.timeScheduled) {
emit([doc.timeScheduled, doc.userId], doc._id); }}"
}
If I do
localhost:5984/orders/_design/Order/_view/by_users_after_time?startKey="[2012-01-01T11:40:52.280Z,f98ba9a518650a6c15c566fc6f00c157]"
I get every result back. Is there a way to access key[1] to do an if doc.userId == key[1] or something along those lines and simply emit on the time?
This would be the SQL equivalent of
select id from Order where userId =
"f98ba9a518650a6c15c566fc6f00c157" and timeScheduled >
2012-01-01T11:40:52.280Z;
I did quite a few Google searches but I can't seem to find a good tutorial on working with multiple keys. It's also possible that my approach is entirely flawed so any guidance would be appreciated.
Upvotes: 0
Views: 4044
Reputation: 4098
The answer actually came from the couchdb mailing list:
Essentially, the Date.parse() doesn't like the +0000 on the timestamps. By doing a substring and removing the +0000, everything worked.
For the record,
document.write(new Date("2012-02-13T16:18:19.565+0000")); //Outputs Invalid
Date
document.write(Date.parse("2012-02-13T16:18:19.565+0000")); //Outputs NaN
But if you remove the +0000, both lines of code work perfectly.
Upvotes: 0
Reputation: 969
don't forget to set an endkey=["f98ba9a518650a6c15c566fc6f00c157",{}], otherwise you get the data of all users > "f98ba9a518650a6c15c566fc6f00c157"
Upvotes: 1
Reputation: 3901
You only need to reverse the key, because username is known:
function (doc) {
if (doc.userId && doc.timeScheduled) {
emit([doc.userId, doc.timeScheduled], 1);
}
}
Then query with:
?startkey=["f98ba9a518650a6c15c566fc6f00c157","2012-01-01T11:40:52.280Z"]
NOTES:
startkey
, not startKey
;startkey
is an array, not a string. Then the double quotes go around the username and date values, not around the array.1
as value, instead of doc._id
, to save disk-space. Every row of the result has an id
field with the doc._id
, then there's no need to repeat it.Upvotes: 1