Make all fields required in Mongoose Make all fields required in Mongoose mongoose mongoose

Make all fields required in Mongoose


You could do something like:

var schema = {  name: { type: String},  value: { type: String}};var requiredAttrs = ['name', 'value'];for (attr in requiredAttrs) { schema[attr].required = true; }var Dimension = mongoose.schema(schema);

or for all attrs (using underscore, which is awesome):

var schema = {  name: { type: String},  value: { type: String}};_.each(_.keys(schema), function (attr) { schema[attr].required = true; });var Dimension = mongoose.schema(schema);


I ended up doing this:

r_string =   type: String  required: true r_number =   type: Number  required: true

and on for the other data types.


All fields properties are in schema.paths[attribute] or schema.path(attribute);

One proper way to go : define when a field is NOT required,

Schema = mongoose.Schema;var Myschema = new Schema({    name : { type:String },    type : { type:String, required:false }})

and make them all required by default :

function AllFieldsRequiredByDefautlt(schema) {    for (var i in schema.paths) {        var attribute = schema.paths[i]        if (attribute.isRequired == undefined) {            attribute.required(true);        }    }}AllFieldsRequiredByDefautlt(Myschema)

The underscore way :

_=require('underscore')_.each(_.keys(schema.paths), function (attr) {    if (schema.path(attr).isRequired == undefined) {        schema.path(attr).required(true);    }})

Test it :

MyTable = mongoose.model('Myschema', Myschema);t = new MyTable()t.save()