0

I’m currently working on Padrino application with CouchDB backend. I need to have a model to store json besides some general strings. The model looks like (in pseudocode):

name: 'UniqueName',
properties: { prop1: val1, prop2: val2 }

I can’t predict how many values of which types are to be stored in properties. Currently I use the generic model:

padrino g model MyModel name:string, properties:string

Before storing properties, I stringify json; on loading I create json from string. I feel that I’m doing wrong. Since CouchDB is ready to store json objects as is, I wonder if there is a way to tell Padrino’s model that the latter field is json for it to be stored natively? Like:

name: 'UniqueName',
properies:
  - prop1: val1, 
  - prop2: val2

I see that I could create a separate collection and refer it by _id from MyModel, but at the moment I want to store it alongside it’s name. Is it possible?

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160

1 Answers1

0

It's not necessary to stringify json, just parse it and store as an array using the JSON standard lib.

original JSON data example:
json_data = [{ prop1: val1, prop2: val2, prop3: val3 }] #store the JSON data from wherever it came
parsed = JSON.parse(json_data.to_json) #store the parsed JSON data into an Array

foo = MyModel.find(1) #find whatever collection you wanna update
foo.properties = parsed
# => [{ prop1: val1, prop2: val2, prop3: val3 }]
foo.save

Your MyModel should then look like the following:

{
  "_id" : "your_generated_id",
  "_rev" : "your_generated_rev",
  "name" : "UniqueName",
  "properties" : [
         { 
           prop1: val1, 
           prop2: val2, 
           prop3: val3 
         }
  ]
}

Remember CouchDB is "schemaless". More details here.

Besto
  • 309
  • 1
  • 13
  • I see CouchDB is schemaless. The only question remains: how did I describe migration, e.g. padrino/rails model? Migration is likely to be ORM-independent and I want to keep it so. – Aleksei Matiushkin Nov 09 '14 at 07:37
  • Padrino uses the [CouchRest ORM](https://github.com/couchrest/couchrest) to talk to CouchDB. What you're trying to do is what's called Casting. See the section [CouchRest - Property Arrays](http://www.couchrest.info/model/properties.html) in Model Properties. Also see [CouchRest_ExtendDocument](https://github.com/couchrest/couchrest_extended_document#general) documentation. So to answer your question, the model/migration would be `property :properties, [String]` – Besto Nov 09 '14 at 16:45