javascript - Couchapp:如何存储文档?

标签 javascript couchdb couchapp

完成 couchapp tutoria 之后l,必须完成最后一步:保存创建的披萨。

为此,我创建了一个 JS 函数“saveToppings”,该函数被执行(如 Firebug 控制台所示)但无法保存我的 JSON 文档并显示消息:

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

所以我明白,我的文档不是 JSON 文档,但我不知道如何正确执行此操作。

这是“saveToppings”函数的代码:

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.");
    }
  });
}

...以及来自控制台的调试:

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

最佳答案

所以,刚刚想通了。

我扩展了我的调试以从我的“浇头”对象中获取对象类型

Object.prototype.toString.call(merged_toppings)

...它们是字符串。所以我现在使用 jquery 创建一个 JSON 对象:

var JSONtoppings = jQuery.parseJSON( merged_toppings );

...它正在运行。完整代码在这里:

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!");
    }
  });
}

关于javascript - Couchapp:如何存储文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983408/

相关文章:

javascript - 如何解决 Angular 核心 element_ref.d.ts 中的给定错误?

javascript - 如何访问 CouchDB 文档的字段

javascript - Angular 6 错误 ReferenceError : "process is not defined" with elasticsearch js

javascript - 我在 Node.JS 应用程序中使用路由,当我尝试从浏览器打开其中一条路由时,出现错误

javascript - Django 。通过js渲染模型参数

authentication - 安全客户端 couchApp/couchDB 用户身份验证

javascript - 在 CouchApp 文件夹结构中将自定义验证函数放在哪里?

couchdb - 如何知道我们何时与远程 CouchDB 失去同步

views - 如何在couchdb中实现复杂的搜索过滤器?我应该避免临时 View 吗?

android - Progressdialog 卡住使用 couchbase