简体   繁体   中英

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM