I am working with PouchDB to store some documents in the browser, I have a collection of objects I managed to db.put, and now I need to "update" them, but without having to manually put the _rev parameter. I know the _rev parameter is required, but I was thinking just storing the updated object as a new document, since I figure its less overhead. My question is, how could I fetch all documents and get only get one (the most recent) pushed document of each one. I'm thinking timestamping them, but I don't want to rely on it. Any orientation would be much appreciated.
1 Answers
You can update single documents without rev by using an update handler. https://docs.couchdb.org/en/latest/ddocs/ddocs.html?#update-functions
Updating multiple docs retrieving the newest
To update multiple docs using a timestamp or a version number could be a posibility:
To get the newest document version you could write a view and reduce it to show the max value:
Your implementation could look like this:
// Your documents
// PUT #1
{
_id: "test_doc_[timestamp],
doc_id: "test_doc",
doctype: "book",
timestamp: [timestamp],
payload: "lorem ipsum"
}
// PUT #2
{
_id: "test_doc_[timestamp + n],
doc_id: "test_doc",
doctype: "book",
timestamp: [timestamp + n],
payload: "dolor sit amet"
}
Getting the newest version of one document
To get the newest version of 'test_doc' you can use _all_docs What the request below does is that it queries all your documents beginning with your doc id, sorts them descending and returns you the top dataset which in your case would be the newest.
GET /db/_all_docs?start_key="test_doc_"&end_key="test_doc_\ufff0"&descending=true&limit=1
Getting the newest version of many documents
To get the newest version of many documents you could write a view and then reduce it:
// view not formated so that it can be used directly
{
"_id": "_design/books",
"views": {
"newest": {
"reduce": "function (key, values, rereduce) {\r\n return Math.max.apply({}, values);\r\n}",
"map": "function (doc) {\n if(doc.doctype === \"book\")\n emit(doc.doc_id, doc.timestamp);\n}"
}
},
"language": "javascript"
}
You can call the view with:
GET /db/_design/books/_view/newest?descending=true&reduce=true&group=true
Sources:
https://docs.couchdb.org/en/latest/ddocs/ddocs.html?#map-functions

- 857
- 1
- 11
- 24