所有字段的屬性都在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