How to add properties to fields with arrays of schemas in mongoose

Guillaume Viguier-Just
1 min readJul 27, 2017

It took me a while to find this one out, so I’m sharing this tip here with the hope that it might be useful for someone else as well.

Let’s say you have the following mongoose database schema:

const emailSchema = new Schema({
type: {
type: String,
enum: ['Work', 'Personal']
},
email: {
type: String
},
validated: {
type: Boolean,
default: false
}
});
const userSchema = new Schema({
name: { type: String },
emails: [emailSchema]
});

My problem was, how do I add some properties, like a validator or required property, to the emails attribute, which is an array of schemas ? Here is how:

const userSchema = new Schema({
name: { type: String },
emails: { type: [emailSchema], required: true }
});

Originally published at https://www.gvj-web.com on July 27, 2017.

--

--