Search code examples
couchdbcouchdb-futon

How to name application specific fields in couchdb


I tried adding my own fields with names like _myappvar and _myotherappvar to documents to distinguish them from data fields. At first it worked but at some point futon starts to complain.

What is the right way to go?

I am using couchdb 0.9.0, this may be old, butI will not be able to upgrade in this iteration.

Edit: I guess _* is reserved for couchdb vars. I could choose something else but is there a best practice or ho are you solving this?

Edit2: This is somehow severe for my application, because it is already live with those fields. I wonder under which circumstances I can keep the parts that work and only apply a new naming for future fields.


Solution

  • You are correct. The CouchDB Document API, Special Fields section explains it.

    Top-level fields may not begin with _.

    CouchDB is relaxed, so the best way to go is the easiest thing for your application. About your specific edits:

    1. One idea is to use the _ suffix instead of a prefix. Another idea is a .myapp field which is an object(namespace) for your internal data. You could combine them too:

      {
        "type": "the document type",
        "var1": "Normal variable 1",
        "var2": true,
        "myapp_": {
          "var": "Something internal",
          "othervar": null,
        }
      }
      

      Now you can reference doc.myapp_.var in your view maps, reduces, etc.

    2. You have a choice. You can bite the bullet and change all documents right now. I don't know your app however I prefer that because you are playing with fire using a _ prefix.

      However, you could also have both types of document and simply teach your map() function how to handle both of them.

      function(doc) {
        if(doc.type == "the document type") {
          if(doc._myappvar) {
            emit(doc._id, doc._myappvar); // The old way
          } else if(doc.myapp_) {
            emit(doc._id, doc.myapp_.var); // The new way
          }
        }
      }
      

    Good luck!