CouchDB: add timestamp on insert and update

隐身守侯 提交于 2021-01-28 22:18:51

问题


How I can add or update timestamp on document when it changes? Currently I have date field, which set from app, but that is not secure and right way if anyone can set time.

I'm tried with validate_doc_update, but no luck: it don't save newDoc changes.


回答1:


In order to do this, you need to send all your changes through update handlers.

To be clear, that means normal writes to the database will not set these timestamps, so you can only reliably do this if your database isn't exposed publicly.




回答2:


For anyone still looking for a solution, this was my implementation of the solution: I used Dominic Barnes response. Here how I implemented it. In the _design/$design_name, I added

{
  "_id": "<design_name>",
  "_rev": "<rev_id>",
  "language": "javascript",
  "views": {
    "some_view_name": {
      "map": "function(doc){emit(doc.id,doc);}"
    }
  },
  "updates": {
    "update_timestamp": "function(doc, req){ 
      if (req && req.body) { 
        var newDoc = JSON.parse(req.body); 
        newDoc['timestamp'] = Date.now().toString(); 
        return [newDoc, JSON.stringify({'ok': true})];
      }
    }"
  }
}

Careful, the "update_timestamp" function should be on one line because it is a json file, so like this:

"updates": {
    "update_timestamp": "function(doc, req){ if (req && req.body) { var newDoc = JSON.parse(req.body); newDoc['timestamp'] = Date.now().toString(); return [newDoc, JSON.stringify({'ok': true})];}}"
}

and then, I call it using a PUT request with the URL: <couch_db_url>/<db_name>/_design/<design_name>/_update/update_timestamp/<id_doc> and adding the document in the body.



来源:https://stackoverflow.com/questions/34271617/couchdb-add-timestamp-on-insert-and-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!