Albert Gao
Albert Gao

Reputation: 3769

Set `required` for object type field in Mongoose

This one works fine:

{
  name: {
    first: { type: String, required: true },
    last: { type: String, required: true }
  }
}

But this one is not working

{
  name: {
    required: true,
    first: { type: String },
    last: { type: String }
  }
}

It won't even start:

/Users/albertgao/codes/temp/aaa/node_modules/mongoose/lib/schema.js:751 throw new TypeError(Invalid schema configuration: \${name}` is not ` + ^

TypeError: Invalid schema configuration: True is not a valid type at path name.required.

How to say that I want name to be required without setting each of its sub-fields?

Thanks

Upvotes: 0

Views: 1186

Answers (1)

BenSower
BenSower

Reputation: 1612

The problem is the field:TYPE shorthand, which shouldn't be mixed with option fields like required. Instead I think you can try to not use shorthands in the parent fields like this:

{
  name: {
    type: { 
       first: String,
       last: String
   },
   required: true
}

or even more explicit:

{
  name: {
    type: { 
       first: { type: String},
       last: { type: String}
   },
   required: true
}

Upvotes: 1

Related Questions