tonyq
tonyq

Reputation: 33

Can a Mongoose schema be inspected to determine if a field is required?

I have a Mongoose schema (excerpt below):

var PersonSchema = new Schema({
  name : { 
      first: { type: String, required: true } 
    , last: { type: String, required: true }   
  } 
  ...

I would like to inspect the schema to identify which fields are required then validate those fields are present in user input. I can test the 'required' attribute of name.first as follows:

var person_schema = require('../models/person');

if (person_schema.schema.paths['name.first'].isRequired) {
  req.assert('first', messages.form_messages.msg_required).notEmpty();

But feel this is unsafe as the internal schema details could change. Is there a better way?

Upvotes: 3

Views: 1245

Answers (1)

Max
Max

Reputation: 8836

Mongoose does this type of validation for you. http://mongoosejs.com/docs/validation.html.

Upvotes: 1

Related Questions