是否可以在CouchDB验证功能中向文档添加字段? [英] Is it possible to add fields to a document in a CouchDB validation function?

查看:72
本文介绍了是否可以在CouchDB验证功能中向文档添加字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转移到CouchDB时丢失的一件事是能够为字段设置默认值。例如,在SQL数据库中,您可以使用名为 date 的字段,默认为 now()。是否有可能在CouchDB中做类似的事情?

One of the things that is lost in the move to CouchDB is the ability to have default values for a field. For example, in an SQL database you can have a field called date that defaults to now(). Is it possible to do something similar in CouchDB?

据我所知,在每次创建和更新操作中运行的唯一代码是 validate_doc_update 设计文档的方法。但是,当我们通过创建虚拟验证来测试它时,我们无法使其工作。这是一个简单的验证函数,它试图设置字段 newDoc.foo ,但它永远不会被保存。

From what I can tell, the only piece of code that gets run on every create and update operation is the validate_doc_update method of a design document. However, when we've tested it by creating a dummy validation, we can't get it to work. Here's a simple validation function that attempts to set the field newDoc.foo, but it never gets saved.

function(newDoc, oldDoc, userCtr) {
    newDoc.foo = "bar!";
}

我们检查并验证了 validate_doc_update 方法被调用,所以看起来如果有办法自动添加字段到CouchDB文档,使用验证功能是不可取的。还有其他任何建议吗?

We've checked and verified that the validate_doc_update method is getting called, so it appears that if there a way to automatically add fields to a CouchDB document, using the validation function isn't the way to go. Any other suggestions?

推荐答案

当您通过视图查看文档时,可以使用某些视图逻辑来应用默认值。

You could use some view logic to apply defaults when you view the doc via a view.

您可以在之后应用更新处理程序它被写入(并且可能在后续更改之后)但是每次都需要另一个调用来调用它。

You could apply an update handler to it after it's written (and possibly after subsequent changes) but that'd require another call to invoke it each time.

我可能会通过创建您插入的文档作为对象来解决这个问题,然后再插入它并在其中应用默认值,那么您写入CouchDB的内容已经正确。

I would probably solve this by creating the document you're inserting as an object before you insert it and having the defaults applied there so what you write to CouchDB is already correct.

这篇关于是否可以在CouchDB验证功能中向文档添加字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆