所有字段的属性都在schema.paths[attribute]
或schema.path(attribute)
;
一个正确的路要走:在不需要一个字段定义,
Schema = mongoose.Schema;
var Myschema = new Schema({
name : { type:String },
type : { type:String, required:false }
})
,并让他们都默认需要:
function AllFieldsRequiredByDefautlt(schema) {
for (var i in schema.paths) {
var attribute = schema.paths[i]
if (attribute.isRequired == undefined) {
attribute.required(true);
}
}
}
AllFieldsRequiredByDefautlt(Myschema)
下划线的方式:
_=require('underscore')
_.each(_.keys(schema.paths), function (attr) {
if (schema.path(attr).isRequired == undefined) {
schema.path(attr).required(true);
}
})
测试:
MyTable = mongoose.model('Myschema', Myschema);
t = new MyTable()
t.save()
如果需要所有字段,你为什么要使用一个无模式的数据库? –
无模式数据库与必填字段无关,您可以在关系数据库中使用非必填字段,反之亦然。 (在我看来) – fernandodof