I am using a Schema as a Subdocument in Mongoose, but I am not able to validate it in its fields.
That's what I have
var SubdocumentSchema = new Schema({
foo: {
type: String,
trim: true,
required: true
},
bar: {
type: String,
trim: true,
required: true
}
});
var MainDocumentSchema = new Schema({
name: {
type: String,
trim: true,
required: true
},
children: {
type : [ SubdocumentSchema.schema ],
validate: arrayFieldsCannotBeBlankValidation
}
});
I want to be sure that every field of the subdocument is not empty.
I found out that this is not possible to validate an Array with standard methods, so I wrote my custom validation function.
By now I have to manually check that all the fields are correct and not empty, but it looks to me like a not really scalable solution, so I was wondering if there was some native method to trigger the Subdocument validation from the MainDocument one.
In the definition of children, it should be [SubdocumentSchema], not [SubdocumentSchema.schema]:
var MainDocumentSchema = new Schema({
name: {
type: String,
trim: true,
required: true
},
children: {
type : [ SubdocumentSchema ],
validate: arrayFieldsCannotBeBlankValidation
}
});
SubdocumentSchema.schema evaluates to undefined so in your current code Mongoose doesn't have the necessary type information to validate the elements of children.