Reputation: 43
I'm working on a project and stuck at a point where the docOne is optional. But if docOne is there, the children of the docOne should be required. Is there any way of achieving this behavior through the schema model? Thank you.
const MySchema = new Schema(
{
name: { type: String },
docOne: {
required: false,
type: {
docTwo: {
required: true,
type: {
isActive: { type: Boolean, required: true },
},
},
},
},
},
{ timestamps: true },
);
Upvotes: 1
Views: 648
Reputation: 2573
If you are using mongoose Mongoose 5.8.0 or above, just add typePojoToMixed: false
to the scheme options and the validations should work fine.
const mySchema = new Schema(
{
// ...Schema definition remains the same
},
{ timestamps: true, typePojoToMixed: false },
);
const myModel = mongoose.model('myModel', mySchema);
const sampleDocument = {
name: 'John Doe',
};
myModel.validate(sampleDocument); // No Error
sampleDocument.docOne = {};
myModel.validate(sampleDocument); // Throws ValidationError for docOne.docTwo
If you are using a lesser version of Mongoose, the other thing that can work is declaring the schema type of the nested objects as a separate schemas:
const docTwoSchema = new Schema({
isActive: { type: Boolean, required: true },
},
// Use the "_id: false" option to avoid an autogenerated _id property
{ _id: false }
);
const docOneSchema = new Schema({
docTwo: {
type: docTwoSchema,
required: true,
}
},
// Use the "_id: false" option to avoid an autogenerated _id property
{ _id: false }
);
const mySchema = new Schema(
{
name: { type: String },
docOne: {
type: docOneSchema,
required: false,
},
},
{ timestamps: true },
);
const myModel = mongoose.model('myModel', mySchema);
const sampleDocument = {
name: 'John Doe',
};
myModel.validate(sampleDocument); // No Error
sampleDocument.docOne = {};
myModel.validate(sampleDocument); // Throws ValidationError for docOne.docTwo
Useful Links
Upvotes: 0
Reputation: 1117
try defining the child schema first, and use the child schema in your parent schema.
this way you can make use of sub-documents / embedded-documents where, you can make only required to true.
you can refer https://mongoosejs.com/docs/subdocs.html and https://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html#:~:text=Embedded%20documents%20are%20documents%20with,error%20handling%20is%20a%20snap! for this.
Upvotes: 1