我正在尝试做的事情:
- 我想将数据(id,数据)添加到数据库。这样做时,我想检查 id 是否已经存在,如果存在,则附加到现有数据。否则添加一个新的(id,数据)条目。
例如:这可能是多个测试中学生 ID 和成绩的数据库。如果数据库中已经存在一个 id,我只想附加到数据库中已有的测试分数,否则创建一个新条目:(id, grades)
- 我已经设置了一个更新处理函数来执行此操作。我明白,默认情况下 couchdb insert 不会执行上述操作。现在 - 我如何检查该 ID 的数据库,如果是,则决定是添加新条目还是追加。我知道有 db.get()。但是,我认为由于更新处理程序函数已经是 db itelf 的一部分,因此可能有更有效的方法。
我在 couchdb wiki 中看到了这个示例代码:
function(doc, req){
if (!doc){
if ('id' in req && req['id']){
// create new document
return [req, 'New Document'];
}
// change nothing in database
return [null, 'Incorrect data format'];
}
doc[id] = req;
return [doc, 'Edited World!'];
}
在这个例子中有一些不清楚的地方:我们从哪里得到 id?通常在添加到 db 时不会显式传入 id。
这是否意味着我们需要显式传递一个名为“_id”的字段?
最佳答案
how do I check the db for that id and if so, decide to whether to add a new entry or append.
假设 HTTP 客户端使用 ID 触发您的更新功能,CouchDB 会为您做这件事。作为documentation describes :
When the request to an update handler includes a document ID in the URL, the server will provide the function with the most recent version of that document
在您找到的示例代码中,更新函数看起来像 function(doc, req)
因此在该函数内部的代码中,变量 doc
将具有现有 文档已经在您的 CouchDB 数据库“内部”。所有来自客户端/用户的传入数据都将被发现somewhere within req
.
所以对于你的情况,它可能看起来像:
function(doc, req){
if (doc) {
doc.grades.push(req.form.the_grade);
return [doc, "Added the grade to existing document"];
} else {
var newDoc = {_id:req.uuid, grades:[req.form.the_grade]};
return [newDoc, "Created new document ("+newDoc._id+") for the grade"];
}
}
如果客户端对 /your_db/_design/your_ddoc/_update/your_update_function/existing_doc_id
执行 POST,那么将触发 if (doc)
的第一部分,因为您将在 doc
变量中获得现有文档(为您预取)。如果客户端只对 /your_db/_design/your_ddoc/_update/your_update_function
执行 POST,则没有提供 doc
,您必须创建一个新的( else
子句)。
请注意,客户端将需要知道 ID 才能更新现有文档。要么跟踪它,查找它,要么——如果你必须并了解缺点——根据已知的东西确定它们。
另外:您提到的 db.get()
可能来自 CouchDB HTTP 客户端 库,并且在任何更新/显示/列表/等。在数据库“本身”中沙盒运行的函数。
关于javascript - 如何从更新处理程序javascript代码中查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475123/