Couchapp: how to store a document?

1.1k Views Asked by At

after having finished the couchapp tutorial, the last step from there has to be done: saving the created pizza.

For this I have created a JS function "saveToppings", which is executed (as the firebug console shows) but fails uppon saving my JSON document with the message:

The document could not be saved: Document must be a JSON object.

So I understand, my doc is no JSON doc, but I don't know how to do this properly.

Here is the code of the "saveToppings" function:

function(e){
var json_toppings = JSON.stringify($$(this).toppings);
var merged_toppings = "{ \"type\":\"topping\", \"contents\":" + json_toppings + "}";

$.log('json_toppings: '+ json_toppings.toString());

$.log('merged_toppings: '+ merged_toppings.toString());

$$(this).app.db.saveDoc(merged_toppings, {
    success : function() {
      alert("Doc saved successfully.");
    }
  });
}

...and the debug from the console:

json_toppings: [{"top":"tomatoes"},{"top":"bacon"},{"top":"cheese"}]
merged_toppings: { "type":"topping", "contents":[{"top":"tomatoes"},{"top":"bacon"},{"top":"cheese"}]}
1

There are 1 best solutions below

0
On BEST ANSWER

So, just figured it out.

I extended my debugging to get the object types from my "toppings" objects with

Object.prototype.toString.call(merged_toppings)

...and they are Strings. So I am now using jquery to create an JSON object:

var JSONtoppings = jQuery.parseJSON( merged_toppings );

...and it's working. The complete code here:

function(e){
var json_toppings = JSON.stringify($$(this).toppings);
var merged_toppings = "{ \"type\":\"topping\", \"contents\":" + json_toppings + "}";

var JSONtoppings = jQuery.parseJSON( merged_toppings );

$.log('json_toppings: '+ json_toppings.toString());
$.log('json_toppings type: ' +  Object.prototype.toString.call(json_toppings)); 
$.log('merged_toppings: '+ merged_toppings.toString());
$.log('merged_toppings type: ' + Object.prototype.toString.call(merged_toppings)); 
$.log('JSONtoppings: '+ JSONtoppings);
$.log('json_toppings type: ' + Object.prototype.toString.call(JSONtoppings));

$$(this).app.db.saveDoc(JSONtoppings, {
    success : function() {
      alert("Clicked the save buttoN!");
    }
  });
}