0

I'm just getting started with Mongoose (v3.8.1) and am experimenting with sub-documents and validation. As far as I understand (from the bottom of this page: http://mongoosejs.com/docs/subdocs.html), the following is the correct way to set the schema up:

var ParentSchema = new Schema({
    name: { type: String, required: true },
    children: [{
        name: { type: String, required: true }
    }]
});

Then I can do the following to create the document / sub-document:

ParentModel.create({
    name: "Parent 1",
    children: [
        { name: "Child 1" },
        { name: "Child 2" },
    ]
}, callback);

This works perfectly and the validation fails if I omit any of the child names. However, if I completely omit the children key, validation passes and an empty array is inserted.

Therefore, is there a way of triggering a validation error if the children key is omitted or am I going about this in the wrong way?

1 Answer 1

1

After some more fiddling I think I've got it! Using the type key to specify the schema allows me to also set required: true. Seems to work ok now.

Updated schema:

var ParentSchema = new Schema({
    name: { type: String, required: true },
    children: {
        type: [{
            name: { type: String, required: true }
        }],
        required: true
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.