Tom
Tom

Reputation: 224

Mongoose - how do I require sub-document data when creating a parent document?

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?

Upvotes: 0

Views: 171

Answers (1)

Tom
Tom

Reputation: 224

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

Upvotes: 1

Related Questions