使用update handler进行文档删除

时间:2013-08-17 14:39:10

标签: couchdb

我需要从CouchDB中删除文档,但首先我需要检查是否满足条件。首先想到的是使用更新处理程序,手动迭代更新处理程序中的所有键并删除没有_前缀的那些键并设置_delete字段到true

我想这应该产生与普通DELETE相同的结果,我是对的吗?

更新

使用@ Kxepal的建议,这就是更新处理程序的样子:

function (doc, req) {
  if (req.query.account_id != doc.account_id) {
    return [doc, '{"error": "invalid account id"}'];
  }
  return [{
    _id: doc._id,
    _rev: doc._rev,
    _deleted: true
  }, 'ok'];
}

1 个答案:

答案 0 :(得分:0)

不是。

当您DELETE文档时,CouchDB会删除_id_rev以外的所有字段(当然,_deleted也在那里)。此信息也称为tombstone

当您向文档添加_deleted: true时,它会被标记为已删除,但所有其他字段仍然存在:

http --json http://localhost:5984/recipes/SpaghettiWithMeatballs

HTTP/1.1 404 Object Not Found
Cache-Control: must-revalidate
Content-Length: 41
Content-Type: application/json
Date: Sat, 17 Aug 2013 14:49:17 GMT
Server: CouchDB/1.4.0+build.c843cef (Erlang OTP/R16B)

{
    "error": "not_found", 
    "reason": "deleted"
}

http --json http://localhost:5984/recipes/SpaghettiWithMeatballs\?rev\=9-ac84157c2206793b7d142f5d8e2c97d0

HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 425
Content-Type: application/json
Date: Sat, 17 Aug 2013 14:48:55 GMT
ETag: "9-ac84157c2206793b7d142f5d8e2c97d0"
Server: CouchDB/1.4.0+build.c843cef (Erlang OTP/R16B)

{
    "_attachments": {
        "my_recipe.txt": {
            "content_type": "text/plain", 
            "digest": "md5-198BPPNiT5fqlLxoYYbjBA==", 
            "length": 85, 
            "revpos": 2, 
            "stub": true
        }
    }, 
    "_deleted": true, 
    "_id": "SpaghettiWithMeatballs", 
    "_rev": "9-ac84157c2206793b7d142f5d8e2c97d0", 
    "description": "An Italian-American dish that usually consists of spaghetti, tomato sauce and meatballs.", 
    "ingredients": [
        "spaghetti", 
        "tomato sauce", 
        "meatballs"
    ], 
    "name": "Spaghetti with meatballs"
}

但是,在压缩过程中,此文档将仅转换为tombstone,仅包含_id_rev_deleted字段。在此之前,这是保持文档中的数据以便轻松撤消删除操作而不请求文档的先前版本的好方法,因为所有内容都可用于最新版本。