0

I'm creating a RESTAPI but upon compiling the npm throws an error message stating

Invalid Schema Configuration

I have tried to look for the solution in official docs as well as on StackOverFlow also but none of them answered my question.

const TeacherSchema = new Schema({

   WorkExperience:[{
              startDate:String,
              endDate:String,
              companyName:String,
              postName:String,
              required:true
        }],
});

The code should compile but it is throwing an error

Mat
  • 202,337
  • 40
  • 393
  • 406
nikhil6041
  • 55
  • 1
  • 8
  • This schema seems invalid because it declares `required: true` as a field in the array - however you provide `true` as a value instead of a schema type. Have a look at this [post](https://stackoverflow.com/questions/27268172/mongoose-schema-to-require-array-that-can-be-empty), it should show you how to fix your issue. – Stock Overflaw Jun 13 '19 at 11:52
  • As @StockOverflaw commented, your mistake is to define `required` as the fifth field of the array object instead of as an attribute of each field (or the required). Anyway, keep in mind that defining the fields as required will only affect when inserting an object in the array but it would be possible to insert a document with no items in the array. – virgiliogm Jun 13 '19 at 12:01
  • You can read [this](http://jasonjl.me/blog/2014/10/23/adding-validation-for-embedded-objects-in-mongoose/) to get more clear understanding – Vibhas Aug 12 '19 at 08:52

1 Answers1

0

You can also add require for every field. I don't think there is a way to add validation as required for an array.

const workExperienceDetails = new Schema({
  startDate: { type: String, required: true },
  endDate: { type: String, required: true }
  companyName: { type: String, required: true }
  postName: { type: String, required: true }
});
const TeacherSchema = new Schema({
   workExperience:[workExperienceDetails],
});
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
  • Thanks for the answer it worked out i tried to look for the solution but is there any problem in defining the schema inside the parent schema – nikhil6041 Jun 14 '19 at 12:11