1

我以以下方式将产品存储在 CouchDB 数据库中:

{
  "_id": "1ce330a867a803fd10082c4513000fe5",
  "_rev": "4-a5eae6f790ea8b9cedea53db50a13fef",
  "type": "Product",
  "name": "Apple",
  "price": 1
}

我想创建一个验证,以确保每个带有 的新文档type Product都有该字段name。我找到的唯一文档是http://guide.couchdb.org/draft/validation.html阅读后我写/复制了这个验证:

function(newDoc, oldDoc, userCtx) {
  function require(field, message) {
    message = message || "Document must have a " + field;
    if (!newDoc[field]) throw({forbidden : message});
  }

  if (newDoc.type == "Product") {
    require("name");
  }
}

比我使用 Fauxton 来创建它:

截屏

但它不起作用。我可以创建这样一个没有name字段的文档。我做错了什么?

4

1 回答 1

1

您必须创建一个新的设计文档。您需要指定适合您情况的语言字段。JavaScript

然后,您必须添加validate_doc_update字段并用您的函数填充它。

作为参考,您可以_replicator查看_design/_replicator.

选择

在命令行上可以使用(注意转义“):

curl -X PUT http://127.0.0.1:5984/shop/_design/product_validation -d '{"validate_doc_update": "function(newDoc, oldDoc, userCtx) { if (newDoc.type == \"product\") { if (!newDoc[\"name\"]) { throw({forbidden: \"missing name\"}) } } }"}'
于 2018-04-28T16:13:07.460 回答