我可以要求在mongodb集合中设置属性吗? (不为null) [英] Can I require an attribute to be set in a mongodb collection? (not null)
问题描述
我可以在mongodb中定义需要设置某些属性的架构.类似于SQL中的NOT NULL
.如果可能的话.这是什么语法?
Can I define a schema in mongodb which requires certain attributes to be set. Much like NOT NULL
in SQL. If that is possible. What is the syntax for this?
我正在使用node.js和猫鼬. 猫鼬v3.6.15 mongodb v2.4.5
I am using node.js and mongoose. mongoose v3.6.15 mongodb v2.4.5
修改 Charles A提供的答案是正确的,但通过查阅文档,我发现在猫鼬中,还可以根据架构定义的要求定义一个字段,如下所示:
Edit The answer provided by Charles A is correct but looking through the documentation I found that in mongoose it is also possible to define a field as required in the schema defenition like this:
foo : {
bar : { type : String, required : true }
}
推荐答案
在Mongoose中,您可以使用 validator 在保存之前检查是否已设置字段.据我所知,无法在Schema上指定需要一个字段,因此它需要更多样板代码.
In Mongoose, you can use a validator to check if a field has been set before you save it. As far as I know, there is no way of specifying on a Schema that a field is required, so it requires a little more boilerplate code.
这篇关于我可以要求在mongodb集合中设置属性吗? (不为null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!