J. Pichardo
J. Pichardo

Reputation: 3115

Required subdocuments Mongoose

I have defined the following Mongoose schemas

var subSchema = new Schema({
    propertySub: {type: String, required: true}
});

var mainSchema = new Schema({
    mainProperty: {type: String, required: true},
    subs: [subSchema]
});

As you may see there is a required property on subSchema, and the problem is that I want a mainSchema to be required to have at least one subSchema, but when I send a

{
    "mainProperty" : "Main"
}

nothing fails.

I tried something like

subs: [{
    type: subSchema,
    required: true
}]

But it throws the following:

TypeError: Undefined type undefined at array subs

So anyway to do this?, maybe with validate I'm new to node and mongoose so an explication will be greatly appreciated

Upvotes: 3

Views: 891

Answers (1)

AJ Funk
AJ Funk

Reputation: 3187

Yes you will either want to use validate, or you can validate with a presave hook if you want. Here's an example of using validate

var mainSchema = new Schema({
    mainProperty: {type: String, required: true},
    subs: {
      type: [subSchema],
      required: true,
      validate: [notEmpty, "Custom error message"]
    }
});

function notEmpty(arr) {
  return arr.length > 0;
}

Upvotes: 3

Related Questions