Search code examples
rubycouchdbcouchrest

CouchRest - checking if document id exists


I've probably just missed it in obvious doco but I can't work out how to check if a doc exists in my db using CouchRest.

I tried db.get(id) but that throws a 404 in my application, and it seems kind of silly to have to try/ catch my way around it.

Is there a simple way to say "if this ID exists -> update, else -> create"?


Solution

  • Quick answer - no.

    Basically, it's not possible to save or update in couch, as updating an existing document required the revision number, and you will need to get it first to see. You will need to handle the 404 here.

    To be more helpful, I'd probably use a method like this:

    def save_or_create(db, doc)
      begin
        rev = db.get(doc['_id'])
        doc['_rev'] = rev
        db.save_doc(doc)
      rescue RestClient::ResourceNotFound => nfe
        db.save_doc(doc)
      end
    end
    

    Untested, but should be close.