سؤال

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"?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I suggest using couchdb update API (>=0.10) when your problem is about create-or-update. Design it just like so:

{
  "updates" : {
    "in_place" : "function(doc, req) {
      var new_doc = null;
      if (req.body) {
        new_doc = JSON.parse(req.body);
      } else {
        return [null, 'No doc given!'];
      }
      if (doc) {
        for(var attr in new_doc) {
          if (attr != '_id' && attr != '_rev') {
            doc[attr] = new_doc[attr];
          }
        }
        return [doc, 'Update OK'];
      } else {
        new_doc['_id'] = new_doc['_id'] || req.uuid;
        return [new_doc, 'Insert OK'];
      }
    }"
  }
}

POST then to $DB/_design/$DESIGN_NAME/_update/in_place or PUT to $DB/_design/$DESIGN_NAME/_update/in_place/$DOC_ID. It's a simple case using bare-metal RestClient, upon which CouchRest was built.

Fully working function based on previous stacker comment (i add ['_rev'] to query):

def save_or_create(db, doc)
    begin
      rev = db.get(doc['_id'])['_rev']
      doc['_rev'] = rev
      db.save_doc(doc)
    rescue RestClient::ResourceNotFound => nfe
      db.save_doc(doc)
    end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top