What I'm trying to do:
- I want to add data (id, data) to db. While doing so, I want to check if the id already exists and if so, append to existing data. else add a new (id, data) entry.
Ex: This could be a db of student id and grades in multiple tests. If an id exists in the db already, I want to just append to the existing test scores already in db, else create a new entry: (id, grades)
- I have setup an update handler function to do this. I understand, couchdb insert by default does not do the above. Now - how do I check the db for that id and if so, decide to whether to add a new entry or append. I know there is db.get(). However, I presume since the update handler function is already part of the db itelf, there may be a more efficient way of doing it.
I see this sample code in the couchdb wiki:
function(doc, req){
if (!doc){
if ('id' in req && req['id']){
// create new document
return [req, 'New Document'];
}
// change nothing in database
return [null, 'Incorrect data format'];
}
doc[id] = req;
return [doc, 'Edited World!'];
}
a few clarifications in this example that's not clear: where do we get the id from? Often the id is not explicitly passed in while adding to db.
Does that mean, we need to explicitly pass a field called "_id"?
CouchDB does this for you, assuming HTTP client triggers your update function using the ID. As the documentation describes:
In the sample code you found, the update function looks like
function(doc, req)
and so in the code inside of that function the variabledoc
will have the existing document already "inside" your CouchDB database. All the incoming data from the client/user will be found somewhere withinreq
.So for your case it might look something like:
If the client does a POST to
/your_db/_design/your_ddoc/_update/your_update_function/existing_doc_id
then the first part of theif (doc)
will be triggered, since you will have gotten the existing document (pre-fetched for you) in thedoc
variable. If the client does a POST to just/your_db/_design/your_ddoc/_update/your_update_function
, then there is nodoc
provided and you must create a new one (else
clause).Note that the client will need to know the ID to update an existing document. Either track it, look it up, or — if you must and understand the drawbacks — make them determinate based on something that is known.
Aside: the
db.get()
you mentioned is probably from a CouchDB HTTP client library and is not availble (and would not work) in the context of any update/show/list/etc. functions that are running sandboxed in the database "itself".