CouchDB:在插入和更新时添加时间戳 [英] CouchDB: add timestamp on insert and update
问题描述
如何在文档更改时添加或更新时间戳?目前,我有 date
字段,该字段是通过应用设置的,但是如果有人可以设置时间,那么这是不安全且正确的方法.
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.
我尝试过 validate_doc_update
,但没有运气:它不保存 newDoc
更改.
I'm tried with validate_doc_update
, but no luck: it don't save newDoc
changes.
推荐答案
对于仍在寻找解决方案的任何人,这是我对解决方案的实现:我使用了Dominic Barnes响应.在这里,我是如何实现它的.在_design/$ design_name中,我添加了
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})];
}
}"
}
}
小心,"update_timestamp"函数应该在一行上,因为它是一个json文件,因此如下所示:
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})];}}"
}
然后,我使用带有URL的PUT请求来调用它:并将文档添加到正文中.
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.
这篇关于CouchDB:在插入和更新时添加时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!