所有字段属性都在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()